matplotlib是基建立在python之上,适用于创建静态,动画和交互式可视化,通常与数据分析模块pandas搭配使用,用于数据的分析和展示,适用于主流的操作系统,如Linux,Win,Mac。
|
|
如果是anaconda中内置的python,这个包是默认自带的;
当用pip安装时,可以使用清华源加速安装;
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
首先导入matplotlib,按照惯例简写为plt
import matplotlib.pyplot as plt
plt.style.use(style) #设置图像风格样式
|
|
|
|
print(plt.style.available) # 查看所有可选的风格
更多参考:https://blog.csdn.net/qq_42505705/article/details/84962815
在绘图之前,需要新建一个画布,它的作用就类似于一张纸,可以在上面画,当绘制的图像过大,超过了界限,就可以预先设置一个合适的大小,当然,这步也可以根据实际情况进行省略;
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=, clear=False, **kwargs)
matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]
x = [1, 2, 3]
y = [1, 2, 3]
# 以下两种写法等价,
plt.plot(x, y, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12)
# plt.flot(x, y, 'go--',linewidth=2, markersize=12)
# 可以在一个画布上绘制多张图片,
y1 = [4, 5, 6]
plt.plot(x, y1, color='red', marker='*', linestyle='solid', linewidth=2, markersize=12)
plt.show()
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style({'font.sans-serif':['simhei','Arial']})
name_list = ['China', 'USA', 'India', 'Russia']
num_list = [14, 3.3, 7.8, 1.46]
plt.bar(range(len(num_list)), num_list, color='rgb',tick_label=name_list,bottom=1)
# plt.bar(range(len(num_list)), num_list, color=['r', 'g', 'b'], tick_label=name_list,bottom=1)
plt.ylabel("人口(亿)")
plt.show()
matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align='center', **kwargs)[source]
y:float or array-like 柱子在y轴上的坐标
width:float or array-like 柱子的宽度,即水平长度
height:float or array-like, 柱子的高度,与垂直柱状图中的宽度相对应 default: 0.8
left:float or array-like,每个柱子在x方向的起始坐标 default: 0
align:柱子同y轴坐标的对齐方式, {‘center’, ‘edge’}, default: ‘center’
tick_lable:list[str] 将相应的纵坐标替换成标签,见代码
更多参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.barh.html
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style({'font.sans-serif':['simhei','Arial']})
name_list = ['China', 'USA', 'India', 'Russia']
num_list = [14, 3.3, 7.8, 1.46]
plt.barh([1, 2, 3, 4], num_list, color='rgb', left=[1, 2, 1, 2], tick_label = name_list)
plt.ylabel("人口(亿)")
plt.savefig('test2.png', bbox_inches='tight')
plt.show()
参考:Python中使用matplotlib画饼图详解
matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=0, 0, frame=False, rotatelabels=False, *, normalize=None, data=None)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style({'font.sans-serif':['simhei','Arial']})
labels = ['大型','中型','小型', '微型'] #定义标签
sizes = [46, 253, 321, 66] #每块值
colors = ['red','yellowgreen','lightskyblue','yellow'] #每块颜色定义
explode = (0, 0, 0.02, 0) #将某一块分割出来,值越大分割出的间隙越大
patches,text1,text2 = plt.pie(sizes,
explode=explode,
labels=labels,
colors=colors,
labeldistance = 1.2,#图例距圆心半径倍距离
autopct = '%3.2f%%', #数值保留固定小数位
shadow = False, #无阴影设置
startangle =90, #逆时针起始角度设置
pctdistance = 0.6) #数值距圆心半径倍数距离
# x,y轴刻度设置一致,保证饼图为圆形
plt.axis('equal')
plt.legend()
plt.savefig('test2.png', bbox_inches='tight')
plt.show()
matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
sns.set_style({'font.sans-serif': ['simhei', 'Arial']})
matplotlib.rcParams['axes.unicode_minus'] = False # 显示负号
font = {'family': 'Times New Roman',
'weight': 'normal',
'size': 15,
}
data = np.random.randn(30)
plt.subplot(121)
# 实现散点图的功能
plt.plot(data1, marker="*", linestyle="", c='red')
plt.title("plt.plot()")
plt.subplot(122)
plt.scatter(range(30), data1, marker="*")
plt.title("plt.scatter()")
plt.savefig('compare.png', bbox_inches='tight')
plt.show()
先在开头添加如下代码,防止中文乱码
import seaborn as sns
sns.set_style({'font.sans-serif':['simhei','Arial']})
matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
# 以下两种写法对label的属性设置等价
font = {'family' : 'Times New Roman',
'weight': 'heavy',
'size': 10,
'c':'red'}
plt.xlabel("XLabel",family='Times New Roman', weight='heavy', size=10, color='red')
plt.ylabel("YLabel", fontdict=font)
NOTE:当label为中文时,设置某些属性时,显示有问题
matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
"""
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-colorblind')
sns.set_style({'font.sans-serif':['simhei','Arial']})
fig = plt.figure(figsize=(8, 8), dpi=None)
plt.plot([1], [1])
plt.plot([2], [2], '*', markersize=40)
plt.plot([3], [3], '*', markersize=40)
plt.plot([4], [4], markersize=40)
plt.text(x=2, y=2, fontsize=20, s="设置在坐标的左下", ha='right', va='top')
plt.text(x=3, y=3, fontsize=20, s="文字默认在坐标的右上")
plt.show()
matplotlib.pyplot.title(label, fontdict=None, loc='center', pad=None, **kwargs)
当在一个图中绘制多种数据时,通过添加图例能更直观的表达每种图形的含义。
matplotlib.pyplot.legend(*args, **kwargs)
labels: 字符串列表,图列的名称
loc: 图例的位置,用多种可选的位置,默认自适应调整,具体参考下面的链接
fontsize: 文字大小 int or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},通过该参数可以调整图例的大小。
labelcolor: str or list, 图例的颜色
markerscale:float, 相对于图中数据标记的大小,default: rcParams[“legend.markerscale”] (default: 1.0)
更多参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
用法:
ax.plot([1, 2, 3], label='Inline label')
ax.legend()
# 等价的写法
line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.legend()
plt.plot([1, 2, 3])
plt.plot([4, 5, 6])
plt.legend(['first line', 'second line'])
增加一个新的坐标轴或选取存在的轴,这里的轴可以认为是一个子图。
matplotlib.pyplot.subplot(*args, **kwargs)
有三种调用方法:
subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
matplotlib.rcParams['lines.linewidth'] = 4
matplotlib.rcParams['axes.titlesize'] = 'xx-large'
sns.set_style({'font.sans-serif': ['simhei', 'Arial']})
fig = plt.figure(figsize=(10, 10), dpi=100)
ax1 = plt.subplot(221) #该行可以换成 ax1 = fig.add_subplot(2,2,1)
#设置X轴、Y轴的刻度范围
#ax1.set_ylim(0, 1)
#ax1.set_xlim(0, 1)
#设置每个刻度对应的标签
#plt.xticks([1, 2, 3, 4], labels=["a", "b", "c", "d"])
plt.plot([1, 2, 3, 4], [4, 5, 7, 8], color="r", linestyle="--")
#在ax1中添加一条线
plt.plot([1, 2, 3, 4], [6, 7, 8, 9], color='#17becf', linestyle="-")
plt.title(label='first') # 设置字体大小与格式
ax2 = plt.subplot(2, 2, 2)
plt.plot([1, 2, 3, 5], [4, 5, 7, 8], color="y", linestyle="-")
plt.title('tow')
ax3 = plt.subplot(223)
plt.plot([1, 2, 3, 4], [4, 5, 7, 8], marker='*', color="g", linestyle="-.")
plt.title('three', y=-0.15)
ax4 = plt.subplot(224)
plt.plot([1, 2, 3, 4], [4, 5, 7, 8], color="b", linestyle=":")
plt.title('four', y=-0.15)
fig.suptitle("四种样式的线条", y=0.05) # 设置大标题及位置
plt.show()
当在一个画布中存在多个子图,为所有的子图添加一个总的标题。
matplotlib.pyplot.suptitle(t, **kwargs)[source]
上面介绍的API中,有些参数即使不设置,如线条的颜色,形状,字体的大小等,也会提供默认的值,当然我们也可以修改默认的参数设置。首先查看默认的属性有哪些
print(matplotlib.rcParams)
会输出一大串预先设定好的属性及取值,下面改变五种默认的属性
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
plt.style.use('seaborn-colorblind')
sns.set_style({'font.sans-serif':['simhei','Arial']})
print(matplotlib.rcParams)
fig = plt.figure(figsize=(8, 8), dpi=None)
# 修改默认的属性值
matplotlib.rcParams['axes.labelpad'] = 20
matplotlib.rcParams['axes.labelcolor'] = 'red'
matplotlib.rcParams['axes.labelsize'] = 15
matplotlib.rcParams['lines.marker'] = '*'
matplotlib.rcParams['lines.markersize'] = 20
x = [1, 2, 3]
y = [1, 2, 3]
plt.plot(x, y)
plt.xlabel('XLabel')
plt.ylabel('YLabel')
plt.show()
对比图如下:
|
|
设置图例的位置
plt.legend(loc='upper right') #设置图例的位置
https://blog.csdn.net/qq_37710333/article/details/108308155
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.ticker import MultipleLocator
x = [1, 3, 2, 4, 6]
y = [10, 20, 30, 40, 50]
# 设置x轴的刻度大小为1
x_major_locator=MultipleLocator(1)
# 设置y轴的刻度大小为10
y_major_locator=MultipleLocator(10)
ax=plt.gca()
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)
plt.plot(x, y, color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)
# 设置x,y轴的范围
plt.ylim(-1, 52)
plt.xlim(0, 7)
plt.show()
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.ticker import MultipleLocator
# 设置多个刻度范围
plt.figure(figsize=(10, 10))
ran = []
x = [1, 21, 23, 25, 60, 70]
y = [10, 20, 30, 40, 50, 60]
# 设置两个刻度范围
ran.extend(range(0, 30, 5))
ran.extend(range(30, 90, 10))
plt.xticks(ran, rotation=70,fontsize=10)
plt.yticks(range(0, 90, 10), fontsize=10)
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.plot(x, y, color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)
plt.legend(["test"], loc="best")
plt.show()
matplotlib.pyplot.savefig(*args, **kwargs)
调用方法:
savefig(fname, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None, metadata=None)
import cv2
import seaborn as sns
from matplotlib import pyplot as plt
img = cv2.imread('picture.jpg')
sns.set_style({'font.sans-serif': ['simhei', 'Arial']})
plt.figure(figsize=(20, 10))
font = {'family': 'Times New Roman',
'weight': 'normal',
'size': 15,
}
s = "label_{0:02d}"
for i in range(16):
plt.subplot(4, 4, i + 1)
plt.imshow(img, 'gray')
plt.xlabel(s.format(i), font)
plt.xticks([]), plt.yticks([]) # 取消刻度
plt.suptitle("拼接图片", fontsize=20, fontweight='bold')
plt.savefig('puzzle.png', bbox_inches='tight')
plt.show()
|
|
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
sns.set_style({'font.sans-serif': ['simhei', 'Arial']})
matplotlib.rcParams['axes.unicode_minus'] = False # 显示负号
plt.figure(figsize=(13, 13))
font = {'family': 'Times New Roman',
'weight': 'normal',
'size': 15,
}
data1 = np.random.randn(30) * 100
data2 = np.random.randn(30) * 100
plt.plot(data1, label="A")
plt.plot(data2, label="B")
plt.axhline(0, linestyle='--', color='green', lw=2) #插入水平线
# plt.axvline(10, linestyle='--', color='green', alpha=0.8) //插入垂直线
plt.ylabel('precision(%)', fontsize=20)
plt.xlabel("classes",labelpad=8.5, fontsize=20)
plt.legend(fontsize=20)
plt.savefig('compare.png', bbox_inches='tight')
plt.show()
from matplotlib import rcParams
rcParams['font.family'] = 'Arial Unicode MS'
import matplotlib.pyplot as plt
tick_name = ['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']
china_gdp = [60872, 75515, 85322, 95704, 104757, 110616, 112333, 123104, 138948, 142799, 147227]
usa_gdp = [149921, 155426, 161970, 167848, 175272, 182383, 187451, 195430, 206119, 214332, 209366]
a = 3
b = 8
x1 = [(i + 1) * b for i in range(11)]
x2 = [(i + 1) * b + a for i in range(11)]
x3 = [(i + 1) * b + a/2 for i in range(11)]
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(1, 1, 1)
plt.bar(x1, china_gdp, width=a, color='yellowgreen',label="中国")
plt.bar(x2, usa_gdp, width=a, color='lightskyblue',label="美国")
ticks = ax1.set_xticks(x3) # 设置刻度
labels = ax1.set_xticklabels(tick_name, rotation=30, fontsize = 'small') # 设置刻度标签
ax1.set_title("中美GDP对比")
plt.xlabel("年份")
plt.ylabel("总GDP产值(亿美元)")
plt.legend() # 显示图例
plt.show()
from matplotlib import rcParams
rcParams['font.family'] = 'Arial Unicode MS'
import matplotlib.pyplot as plt
tick_name = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
cont = [5324.566083283042, 3194.3816086491624, 2370.236763831053, 1987.694984401248, 2155.7504175614413, 1709.760237388724, 1912.9140811455848, 1615.6501012990107, 1349.456136202412, 1810.7831325301204]
treat = [6092.455656759347, 3475.5420248328555, 3049.4914031501744, 2085.9832935560858, ]
# 23
num_list = [0.016082643, 0.007536573, 0.004361351, 0.007964208, 0.006583216, 0.002371007, 0.00502453, 0.003455287, 0.001115849, 0.013595492]# num_list_r = [0.0067604792575306424] * 10# # 24# num_list = [0.018650344, 0.006166104, 0.005329947, -7.46E-04, 0.00210835, 0.004344219, 0.003247764, 0.003496084, 2.46E-04, 0.008642287]# num_list_r = [0.005346123524244836] * 10# # 25# num_list = [0.017649752, 0.003290102, 0.001193554, 0.005288239, -0.002659459, 0.005013964, 0.004466062, 0.005354266, 0.00111815, 0.004642821]
num_list_r = [0.004483605580702439] * 10
# 调节柱子的
a = 5
# 调节柱子间的距离
b = 13
x1 = [(i + 1) * b for i in range(10)]
x2 = [(i + 1) * b + a for i in range(10)]
x3 = [(i + 1) * b + a/2 for i in range(10)]
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(1, 1, 1)
#调节字体大小
fontsize = 8
for i in range(10):
if(num_list[i] < 0):
plt.text(x=x1[i], y=num_list[i], fontsize=fontsize, s=format(num_list[i], '.4f'), ha='center', va='top')
else:plt.text(x=x1[i], y=num_list[i], fontsize=fontsize, s=format(num_list[i], '.4f'), ha='center', va='bottom')
if (num_list_r[i] < 0):
plt.text(x=x2[i], y=num_list_r[i], fontsize=fontsize, s=format(num_list_r[i], '.4f'), ha='center', va='top')
else:
plt.text(x=x2[i], y=num_list_r[i], fontsize=fontsize, s=format(num_list_r[i], '.4f'), ha='center', va='bottom')
plt.bar(x1, num_list, width=a, color='yellowgreen',label="T=1")
plt.bar(x2, num_list_r, width=a, color='lightskyblue',label="T=0")
ticks = ax1.set_xticks(x3)
# 设置刻度
labels = ax1.set_xticklabels(tick_name, rotation=0, fontsize = 'small')
# 设置刻度标签
ax1.set_title("uv_rpm 十分位图")
plt.ylabel("delta uv_cxr")
plt.xlabel("uplift十分位点")
plt.legend()
plt.show()
首先下载SimHei字体,网上搜一下,到处都是。
下载完之后,看下matplotlib库字体的存放路径
import matplotlib as plt
print(plt.get_data_path())
本人mac系统,输出路径如下:
/Users/lw/.virtualenvs/transformer/lib/python3.6/site-packages/matplotlib/mpl-data
进入到路径所示的文件夹,应该如下所示:
刷新下配置
from matplotlib.font_manager import _rebuild
_rebuild() #reload一下
完成上面三步,应该就能正常显示中文了,如果还是不行,建议仔细检查下,重启IDE试试。