matplotlib简单的条形图应用——二手车销量
用pandas从csv文件中获取数据
用到的库:
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
二手车数据获取:https://blog.csdn.net/qq_42776455/article/details/84872544 ,然后用pandas获取csv文件的内容:
data = pd.read_csv('second_car.csv',usecols=['carName'])
df = pd.DataFrame(data)
print(df)
统计宝马,奔驰的个数:
baoma = 0
benchi = 0
for carName in df["carName"]:
if '宝马' in carName:
baoma += 1
elif '奔驰' in carName:
benchi += 1
生成条形图并保存
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
# 横坐标显示的刻度值
lable_list = ['宝马','奔驰']
num_list = [baoma,benchi]
x = range(len(num_list))
# y轴取值范围
plt.ylim(700,750)
plt.title("不同品牌汽车销量")
plt.ylabel("销量")
plt.xlabel("汽车品牌")
# 设置bars
bars = plt.bar(left=[index+0.1 for index in x],height=num_list,width=0.4,color='pink',alpha=0.8,edgecolor='black')
# plt.xticks() 参数1,x轴上对应的值,参数2:显示的参数
plt.xticks([index+0.1 for index in x],lable_list)
# 设置文本
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x()+ bar.get_width() / 2 , height+1 ,str(height),ha="center", va="bottom")
plt.savefig('01.png')
plt.show()
# plt.text()还可以设置其它的参数,比如:
# ha:horizontalalignment(水平对齐)
# va:verticalalignment(垂直对齐)
# fs:文字大小
效果:
第一次做图,效果一般,多加学习。