一、颜色
二、实例
import pandas as pd
import matplotlib.pyplot as plt
def age_pie():
plt.rcParams['font.family'] = 'SimHei'
df = pd.read_csv("user.csv", sep=";", header=None, names=["user_id", "location", "age"],
encoding='gbk')
df[(df.age == '41"')].index.tolist()
df = df.drop([1305])
df[['age']] = df[['age']].astype(float)
labels = ['10-20', '20-30', '30-40', '40-50', '50-60']
sizes = [len(df[(df.age >= 10) & (df.age < 20)]), \
len(df[(df.age >= 20) & (df.age < 30)]), \
len(df[(df.age >= 30) & (df.age < 40)]), \
len(df[(df.age >= 40) & (df.age < 50)]), \
len(df[(df.age >= 50) & (df.age < 60)])]
explode = (0, 0.05, 0, 0, 0)
colors = ['tomato', 'lightskyblue', 'goldenrod', 'green', 'y']
plt.figure(figsize=(8, 6))
plt.pie(sizes, explode=explode, labels=labels, colors=colors, \
autopct='%1.1f%%', shadow=False, pctdistance=0.8, \
startangle=90, textprops={'fontsize': 16, 'color': 'w'})
plt.title('读者年龄分布图')
plt.axis('equal')
plt.legend(loc='upper right')
plt.savefig('age.png', dpi=600)
plt.show()
print(age_pie())
三、代码解析
3.1显示正负号
import matplotlib.pyplot as plt
plt.rcParams['axes.unicode_minus']=False
3.2显示中文
plt.rcParams['font.family'] = 'SimHei'
黑体 SimHei
微软雅黑 Microsoft YaHei
微软正黑体 Microsoft JhengHei
新宋体 NSimSun
新细明体 PMingLiU
细明体 MingLiU
标楷体 DFKai-SB
仿宋 FangSong
楷体 KaiTi
仿宋_GB2312 FangSong_GB2312
楷体_GB2312 KaiTi_GB2312
3.3找出不合法数据
import pandas as pd
df[(df.age == '41"')].index.tolist()
3.4删除那一行
df = df.drop([1305])
3.5显示图例
plt.legend(loc='upper right')
3.6保存为图片
plt.savefig('age.png', dpi=600)