一、中文显示

        matplotlib中一般是显示不了中文的,需要进行设置才可以。

方法一:指定字体的路径

        需要中文的字体包,一般windows自带的字体包都在C:\Windows\Fonts路径下,

custom_font = matplotlib.font_manager.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf')   # 指定路径

plt.xlabel(u"横坐标xlabel",fontproperties=custom_font)

方法二:通过matplotlib自带的字体包直接设置

plt.rcParams['font.sans-serif']=['STSong'] # 中文宋体

plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号

['STSong']中文宋体['SimHei']中文黑体['Kaiti']中文楷体['Lisu']中文隶书['FangSong']中文仿宋['YouYuan']中文幼圆

二、绘制折线图

语法:plt.plot(x,y,format_string,**Kwargs)

参数: x :代表x轴数据,可以是列表或数组

            y :代表y轴数据,可以是列表或数组

            format_string :控制曲线的绘制风格,下面有详细解释

            **kwargs :其他参数,都要放在最后面,里面有这些东西:

                                        color                          颜色,例如:color = 'b'

                                        linestyle                     线条风格,例如:linestyle = ':'

                                        marker                       标记风格,例如:marker = 'o'

                                        markerfacecolor        标记颜色,例如:markerfacecolor = 'blue'

                                        markersize                 标记点大小,例如:markersize='2.5'

                                        linewidth                     线条宽度,例如:linewidth = 4

颜色说明线条风格说明标记风格说明'b'蓝色’-‘实线'.'点标记'g'绿色’--‘破折现','像素标记'r'红色’-.‘点划线'o'实心圈标记'c'青绿色':'虚线'v'倒三角标记'#008000'RGB某种颜色''''无线条'^'上三角标记'm'洋红色'>'右三角标记'y'黄色'<'左三角标记'k'黑色'1'下花三角标记'w'白色'2'上花三角标记'0.8'灰度值字符'3'左花三角标记'4'右花三角标记's'实心方形标记'p'实心五角标记'*'星型标记

x = [1,2,3,4]

y = [2,2,2,2]

plt.plot(x,y,linewidth=5) # 放入绘制数据和风格

plt.rcParams['font.sans-serif']=['STSong'] # 中文宋体

plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号

plt.title('标题',fontsize=20) # 显示标题

plt.xlabel('时间 hour',fontsize=20) # 显示x轴名称

plt.ylabel('气温 ℃',fontsize=20) # 显示y轴名称

plt.axis([0,6,0,100]) # 设置x轴显示范围为0-6,y轴显示范围为0-100

plt.show()

三、绘制柱状图

names = ['2016', '2017', '2018']

values = [1, 10, 100]

plt.bar(names, values)

plt.show()

四、绘制饼图

import matplotlib.pyplot as plt

# 指定饼图的每个切片名称

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

# 指定每个切片的数值,从而决定了百分比

sizes = [15, 30, 45, 10]

explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()

ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',

shadow=True, startangle=90)

ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

五、绘制散点图

names = ['2016', '2017', '2018', '2019', '2020']

values = [75, 78, 100, 150, 210]

plt.scatter(names, values)

plt.show()

六、多个子图

subplot 方法可以用来创建多个子图(axes)。 前面的示例中,我们并没有创建子图,其实, matplotlib缺省会帮我们调用 plt.subplot(1,1,1) 指定 1行,1列,共1个子图,当前子图为第1个,如果你想指定更多的子图,可以这样,

import matplotlib.pyplot as plt

import numpy as np

# arange 就像 Python中的range

# 从 0 到 5 步长为 0.2

t = np.arange(0, 5, 0.2)

# 指定2行,1列,共两个axe,当前使用第1个绘图块

plt.subplot(2,1,1)

plt.plot(t, t**2, 'b.')

# 当前使用第2个绘图块

plt.subplot(2,1,2)

plt.plot(t, t**2, 'r-')

plt.show()

七、多个绘图

matplotlib 每个绘图区都对应一个 Figure 对象。

一个绘图 Figure 对象 里面可以包含多个 subplot对象。

而我们的程序可以同时打开多个绘图 Figure 对象。

比如下图,你可以发现有两个绘图窗口,对应两个 Figure 对象

前面的示例中,我们并没有声明创建Figure对象,其实是默认使用了 matplotlib 缺省Figure 对象。

默认Figure ,也就是相当于调用 plt.figure(1) 指定第一个绘图。

我们可以像下面这样创建多个Figure

import matplotlib.pyplot as plt

plt.figure(1) # the first figure

plt.subplot(211) # the first subplot in the first figure

plt.plot([1, 2, 3])

plt.subplot(212) # the second subplot in the first figure

plt.plot([4, 5, 6])

plt.figure(2) # a second figure

plt.plot([4, 5, 6]) # creates a subplot(111) by default

plt.figure(1) # figure 1 current; subplot(212) still current

plt.subplot(211) # make subplot(211) in figure1 current

plt.title('Easy as 1, 2, 3') # subplot 211 title

plt.show()

八、图形中的文字

import matplotlib.pyplot as plt

import numpy as np

mu, sigma = 100, 15

x = mu + sigma * np.random.randn(10000)

n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)

# x轴标题

plt.xlabel('Smarts')

# y轴标题

plt.ylabel('Probability')

# 子图标题

plt.title('Histogram of IQ')

# 指定坐标处添加文本

plt.text(60, .025, r'$\mu=100,\ \sigma=15$')

plt.axis([40, 160, 0, 0.03])

plt.grid(True)

plt.show()

九、一些不常用的方法

x轴刻度文字垂直 有时候我们作图时,x轴文字内容比较长,会出现重叠,这时需要x轴刻度文字垂直,可以如下设置

import matplotlib.pyplot as plt

# 设定字体为微软雅黑

plt.rcParams['font.family'] = 'Microsoft Yahei'

# x刻度垂直,否则字会重叠

plt.xticks(rotation=-90)

# 加长底部空间,否则文字显示不全

plt.subplots_adjust(bottom=0.45)

 图像截图保存

plt.savefig('peaks-valleys.png') 将图像截图保存

plt.legend() 

plt.legend(loc=' ') 设置图例位置

fontsize : int or float or {‘xx-small’,‘x-small’,‘small’,‘medium’,‘large’,‘x-large’,‘xx-large’} 设置图例字体大小

plt.legend(loc='best',frameon=False) #去掉图例边框

plt.legend(loc='best',edgecolor='blue') #设置图例边框颜色

plt.legend(loc='best',facecolor='blue') #设置图例背景颜色,若无边框,参数无效

legend = plt.legend(["BJ", "SH"], title='Beijing VS Shanghai') 设置图例的标题

#或者

plt.plot(["BJ", "SH"],loc='upper left',title='Beijing VS Shanghai')

legend = plt.legend([p1, p2], ["BJ", "SH"]) 设置图例名字及对应关系

示例: 

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(0,10,1)

plt.plot(x,x,'r--',x,np.cos(x),'g--',marker='*')

plt.xlabel('row')

plt.ylabel('cow')

plt.legend(["BJ","SH"],loc='upper left',loc='upper left')

plt.show()

参考链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: