import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches #设置子图需要的包
import matplotlib.patches as patches
plt.rcParams['font.sans-serif']=['Simhei']#显示中文,
plt.rcParams['axes.unicode_minus']=False#显示负号
df_raw = pd.read_csv("C:/Users/GYX/Desktop/mpg_ggplot2.csv")
df = df_raw[["cty","manufacturer"]].groupby("manufacturer").mean() #提取制造商和公里每加仑
df.sort_values('cty',inplace=True)
df.reset_index(inplace=True)
fig, ax = plt.subplots(figsize=(16,10),facecolor="white",dpi=80) #设置画布的颜色和大小和分辨路
ax.vlines(x=df.index,ymin=0,ymax=df.cty,color="firebrick",alpha=0.8,linewidth=20)#设置子图的数据颜色透明度宽度
plt.rcParams['font.sans-serif']=['Simhei']#显示中文
for i,cty in enumerate(df.cty):#将数据和序号打包
ax.text(i,cty+0.5,round(cty,1),horizontalalignment='center')#text()函数是加注释,text(横坐标,纵坐标,居中)
#装饰4
ax.set_title("城市里程柱状图",fontdict={"size":20})
ax.set(ylabel='城市公里/加仑',ylim=(0,30))
plt.xticks(df.index #横坐标
,df.manufacturer.str.upper() #df.manufacturer 是显示标尺的内容,str是转成字符串,upper是大写
,rotation=60 #旋转60度
,horizontalalignment='center'
,fontsize=12)
p1 = patches.Rectangle((0.57,-0.005)
,width = .33
,height=.13
,alpha=0.5
,facecolor='green'
,transform=fig.transFigure)
p2 = patches.Rectangle((0.125,-0.005)
,width = .445
,height = .13
,alpha = 0.5
,facecolor = 'red'
,transform=fig.transFigure)
fig.add_artist(p1)
fig.add_artist(p2)
排序图
最新推荐文章于 2023-02-06 23:19:05 发布