[学习笔记] matplotlib 条形图、折线图、饼图

官方文档 http://matplotlib.org/

条形图

  • bar 一组数据生成条形图
import numpy as np
import matplotlib.pyplot as plt
N=5
y=[20,10,30,25,15]
index = np.arange(N) # 生成横坐标
plt.bar(index,y,width=0.5,color='b') #条形图 left横坐标 高度height color为颜色,width为宽度 垂直
plt.show()
  • bar 图形高度叠加
import matplotlib.pyplot as plt
import numpy as np

fr_list = np.arange(3)
fr_list1 = [281, 148, 23]
fr_list2 = [100,100,100]
plt.bar(fr_list,fr_list1,width=0.3)
plt.bar(fr_list,fr_list2,width=0.3 , bottom=fr_list1)
plt.show()
  • bar 图形并列排列
import matplotlib.pyplot as plt
import numpy as np

fr_list = np.arange(3)
fr_list1 = [281, 148, 23]
fr_list2 = [100,100,100]
plt.bar(fr_list,fr_list1,width=0.3)
plt.bar(fr_list+0.3,fr_list2,width=0.3) # fr_list+0.3 宽度0.3,刚好可以并列排列
plt.show()
  • np.arange 用法
>>> np.arange(3)
array([0, 1, 2])

>>> np.arange(1,3,0.3) # 开始  结束  步长
array([ 1. ,  1.3,  1.6,  1.9,  2.2,  2.5,  2.8])

>>> np.arange(1,12,2)
array([ 1,  3,  5,  7,  9, 11])
  • 横向条形图 barh
import matplotlib.pyplot as plt
import numpy as np

fr_list = np.arange(3)
fr_list1 = [281, 148, 23]

plt.barh(fr_list,fr_list1,height=0.5) #height 柱状体的宽度
plt.show()
  • 设置标题、图像名,柱状体标签 等其他设置
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
# 设置中文和负数正常显示
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

fr_list = np.arange(3)
fr_list1 = [281, 148, 23]
plt.xlabel(" 数量") # 纵坐标标签
plt.ylabel("年份") #横坐标标签
plt.title("分析图") # 标题
rects1 = plt.bar(fr_list,fr_list1,width=0.3,label = "1季度")
plt.legend() # 题注 与bar中的label 对应
for rect in rects1:
    height = rect.get_height()
    plt.text(rect.get_x() + rect.get_width() / 2, height+1, str(height), ha="center", va="bottom")  
    # ha='center', va= 'bottom'代表horizontalalignment(水平对齐)、verticalalignment(垂直对齐)的方式,fontsize则是文字大小
plt.show()

'''
在python的matplotlib库中分别可用bar、barh、plot函数来构建它们,
再使用xticks与yticks(设置坐标轴刻度)、
xlabel与ylabel(设置坐标轴标签)、title(标题)、legend(题注)、
xlim与ylim(设置坐标轴数据范围)、grid(设置网格线)等命令来装饰图形
'''

折线图

  • 示例
import matplotlib.pyplot as plt
import numpy as np
import matplotlib

matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

x = np.arange(3)
y = [100,130,1800]
plt.xlabel("xxx")
plt.ylabel("yyy")
plt.title("xxxyyy")
rect1 = plt.plot(x,y,label="图例",ls= '--',lw = '5',c = 'r',marker='o', mec='r', mfc='w')
plt.legend()
for a,b in zip(x,y):
    plt.text(a, b+0.2, str(b), ha="center", va="bottom")
plt.show()
  • 其他
'''
legend方法可接受一个loc关键字参数来设定图例的位置,可取值为数字或字符串
0: ‘best'  1: ‘upper right' 2: ‘upper left'      3: ‘lower left'
4: ‘lower right'   5: ‘right'    6: ‘center left'    7: ‘center right'
 8: ‘lower center'   9: ‘upper center'    10: ‘center'

plot方法的关键字参数color(或c)用来设置线的颜色。可取值为:
     b: blue
     g: green
     r: red
     c: cyan
     m: magenta
     y: yellow
     k: black
     w: white
plot方法的关键字参数linestyle(或ls)用来设置线的样式。可取值为:
-, solid
--, dashed
-., dashdot
:, dotted
'', ' ', None


设置plot方法的关键字参数linewidth(或lw)可以改变线的粗细,其值为浮点数。

marker
以下关键字参数可以用来设置marker的样式:

marker
markeredgecolor 或 mec
markeredgewidth 或 mew
markerfacecolor 或 mfc
markerfacecoloralt 或 mfcalt
markersize 或 ms
其中marker可取值为:

'.': point marker
',': pixel marker
'o': circle marker
'v': triangle_down marker
'^': triangle_up marker
'<': triangle_left marker
'>': triangle_right marker
'1': tri_down marker
'2': tri_up marker
'3': tri_left marker
'4': tri_right marker
's': square marker
'p': pentagon marker
'*': star marker
'h': hexagon1 marker
'H': hexagon2 marker
'+': plus marker
'x': x marker
'D': diamond marker
'd': thin_diamond marker
'|': vline marker
'_': hline marker
 '''

饼图

import matplotlib.pyplot as plt
import matplotlib

matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

label_list = ["dogs", "cats", "others"]    # 各部分标签
size = [550, 350, 100]    # 各部分大小
color = ["red", "green", "blue"]     # 各部分颜色
explode = [0.05, 0, 0]   # 各部分突出值
"""
绘制饼图
explode:设置各部分突出
label:设置各部分标签
labeldistance:设置标签文本距圆心位置,1.1表示1.1倍半径
autopct:设置圆里面文本
shadow:设置是否有阴影
startangle:起始角度,默认从0开始逆时针转
pctdistance:设置圆内文本距圆心距离
返回值
l_text:圆内部文本,matplotlib.text.Text object
p_text:圆外部文本
"""
plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1, autopct="%1.1f%%", shadow=False, startangle=90, pctdistance=0.6)
plt.axis("equal")    # 设置横轴和纵轴大小相等,这样饼才是圆的
plt.legend()
plt.show()

'''
l_text = plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1, autopct="%1.1f%%", shadow=False, startangle=90, pctdistance=0.6)
print(l_text)
'''

#保存图片 dpi为图像分辨率,bbox_inches = 'tight'英寸
# 注意在plt.show() 方法前调用保存
plt.savefig('e:/tj/month/123.png',dpi=600,bbox_inches = 'tight')


猜你喜欢

转载自blog.csdn.net/vs_hero_2019/article/details/86684962