饼图
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist # https://www.jianshu.com/p/af8a448d4d4f
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 #有中文出现的情况,需要u'内容'
my_dpi=480
plt.figure(figsize=(2400/my_dpi,2400/my_dpi),dpi=my_dpi)
# 饼图
# 参考: https://zhuanlan.zhihu.com/p/203527939
plt.pie(x=[460,320,120,80,20], labels=['Li 500亿元','pv 300亿元','H2 100亿元','car 80亿元','others 20亿元'],#为饼图添加标签说明
autopct='%1.f%%',
startangle=-200,#饼图的开始角度,默认为0度
counterclock=False,#关闭逆时针显示
)
plt.savefig("饼图.png") # 在 plt.show() 之前保存
plt.show()
柱状图和折线图共用坐标轴
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist # https://www.jianshu.com/p/af8a448d4d4f
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 #有中文出现的情况,需要u'内容'
my_dpi=480
# 柱状图与折线图
"""参考:
https://juejin.cn/post/6998428139110006791
https://blog.csdn.net/candice5566/article/details/121444185
https://zhuanlan.zhihu.com/p/25128216
"""
# 数据
citys = ["sz","sh","bj","cz","suz","nj","cd"] # 城市
output_value=[6070.5,2100,2000,3918.1,2668,1600,1000] # 产值
growth_rate = [26.6,55,25,96.5,27.4,20,100] # 增速
fig, ax = plt.subplots(figsize=(3200/my_dpi,2400/my_dpi),dpi=my_dpi)
# 网格线
plt.grid(color = 'r', linestyle = ':', linewidth = 0.5)
# 取消边框
for key, spine in ax.spines.items():
# 'left', 'right', 'bottom', 'top'
if(key == 'top' or key == 'right'):
spine.set_visible(False)
# 绘柱状图
bar= plt.bar(range(len(output_value)), output_value, tick_label=citys)
# 设置标题
# plt.title("Detection results")
# 为两条坐标轴设置名称
# plt.xlabel("城市")
plt.ylabel("2022年产值(亿元)")
# 显示数据标签
plt.bar_label(bar, label_type='edge',padding=5)
# # 画折线图
# https://www.cnblogs.com/ltkekeli1229/p/16199597.html
ax2 = plt.twinx() # 添加共享x轴的子图
ax2.spines['top'].set_visible(False)
# ax2.spines['right'].set_visible(False)
# # 添加折线百分比
for x, y in zip(citys, growth_rate):
plt.text(x, y+2, "%.2f%%" % y, ha='center', va='bottom', fontsize=7.5)#y_axis_data1加标签数据
ax2.set_ylabel("增速(%)")
# 设置坐标轴范围
ax2.set_ylim([0, 110]);
#'bo-'表示蓝色实线,数据点实心原点标注,线的形状('s'方块,'o'实心圆点,'*'五角星
ax2.plot(citys, growth_rate,'bo--')
plt.savefig("柱状图折线图.png")
plt.show()
正文完