Matplotlib 简单应用

基本绘图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.plot([1,2,3,4,5],[1,2,3,4,5],linestyle = '--',color='r',linewidth=3,marker ='o',markerfacecolor = 'y',markersize = 10,alpha =0.5)
plt.plot([1,2,3,4,5],[1,3,4,5,9],'o',color='g')
plt.plot([1,2,3,4,5],[1,4,9,16,25],'rs',color='b')
plt.xlabel('xlabel',fontsize=20)
plt.ylabel('ylabel')
xtext = 2    # 注释的X位置
ytext = 15    # 注释的y位置
plt.annotate("It's note.",xy=(xtext,ytext),xytext=(xtext-1,1.1*ytext),arrowprops = dict(facecolor = 'black',shrink = 1))
plt.grid()
plt.show()

在这里插入图片描述

更换风格

# 查看可用风格
print(plt.style.available)
# 使用风格
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('dark_background')  # 在最开始使用,否则可能不生效
plt.plot([1,2,3,4,5],[1,2,3,4,5],linestyle = '--',color='r',linewidth=3,marker ='o',markerfacecolor = 'y',markersize = 10,alpha =0.5)
plt.plot([1,2,3,4,5],[1,3,4,5,9],'o',color='g')
plt.plot([1,2,3,4,5],[1,4,9,16,25],'rs',color='b')
plt.xlabel('xlabel',fontsize=20)
plt.ylabel('ylabel')
xtext = 2    # 注释的X位置
ytext = 15    # 注释的y位置
plt.annotate("It's note.",xy=(xtext,ytext),xytext=(xtext-1,1.1*ytext),arrowprops = dict(facecolor = 'black',shrink = 1))
plt.grid()
plt.show()

在这里插入图片描述

  • 手绘风格
plt.xkcd()   # 画图前增加这个语句即可

在这里插入图片描述

条形图

xdata = [1,2,3,4,5]
ydata = [1,3,5,8,12]
plt.bar(xdata,ydata)
plt.axhline(3,color = 'r',linewidth=2,linestyle = '--')   # 画一条线
plt.show()

在这里插入图片描述

  • 根据要求,设置不同颜色
xdata = [1,2,3,4,5]
ydata = [1,3,5,8,12]

plot1 = plt.bar(xdata,ydata,color ='g')
for plot,height in zip(plot1,ydata):
    if height <5:
        plot.set(color = 'red')

plt.axhline(3,color = 'r',linewidth=2,linestyle = '--')   # 画一条线
plt.show()

在这里插入图片描述

x =np.linspace(0,10,200)
y1 = 2*x + 1
y2 = 3*x + 2
y_mean = 0.5 * x *np.cos(2.5*x)+2.5*x +1.5
plt.fill_between(x,y1,y2,color = 'red')
plt.plot(x,y_mean,color = 'black')
plt.show()

在这里插入图片描述

x1 = np.array(np.abs(np.random.randn(50)))
x2 = np.array(np.abs(np.random.randn(50)))

bar_labels = ['label_%s' %i for i in np.arange(50)]

fig = plt.figure(figsize=(10,8))
y_pos = np.arange(len(x1))   # 这里是一个数组
y_pos = [ x for x in y_pos]   # 转化成列表

plt.barh(y_pos,x1,color = 'g',alpha= 0.5)
plt.barh(y_pos,-x2,color = 'b',alpha = 0.5)
plt.xlim(-max(x2)-0.5,max(x1)+0.5)
plt.ylim(min(y_pos)-2,max(y_pos)+2)
plt.show()

在这里插入图片描述

np.random.seed(0)
df = pd.DataFrame({'line 1':np.random.rand(20),
                    'line 2':np.random.rand(20) * 0.8,
                    'line 3':np.random.rand(20) * 1.1})

print(df)

fig,ax = plt.subplots()
df.plot.bar(ax = ax,stacked = True)
plt.show()

在这里插入图片描述

箱型图

data = [np.random.normal(0,std,100) for std in range(1,5)]
print(data)
fig = plt.figure(figsize=(10,8))
box_chart = plt.boxplot(data,notch=False,sym='.',vert=True,patch_artist=True)  # sym='s' 表示用方框表示,o 圆圈,.小圆圈; vert 为垂直或者水平;
plt.title('BOX Chart')
plt.xticks([y+1 for y in range(len(data))],['X1','X2','X3','X4'])

colors = ['pink','lightblue','lightgreen','blue']

for pathch ,color in zip(box_chart['boxes'],colors):
    pathch.set_facecolor(color)

plt.show()

在这里插入图片描述

小提琴图

fig,axes = plt.subplots(nrows=1,ncols=2,figsize = (12,5))
data = [np.random.normal(0,std,100) for std in range(6,10)]
axes[0].violinplot(data,showmeans = True, showmedians =True)
axes[0].set_title('violin plot')
axes[1].boxplot(data)
axes[1].set_title('box plot')

for ax in axes:
    ax.yaxis.grid(True)
    ax.set_xticks([y+1 for y in range(len(data))])
plt.setp(axes,xticks =[y+1 for y in range(len(data))],xticklabels=['x1','x2','x3','x4'] )

plt.show()

在这里插入图片描述

  • 直方图
import math
x = np.random.normal(loc = 0.0, scale=1.0, size = 300)
width = 0.5
bins = np.arange(math.floor(x.min())- width, math.ceil(x.max())+width,width)
fig = plt.figure(figsize=(10,5))
ax =  plt.subplot(111)
plt.gcf().subplots_adjust(bottom=0.25)   # 调节xlabel的位置的大小
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
labels = ['For Long Name' for i in range(10)]
ax.set_xticklabels(labels,rotation =45,)
plt.tick_params(bottom = False,top = False,left=True,right = False)  # 设置刻度
# plt.grid()
plt.hist(x,alpha =0.5,bins=bins)
plt.show()

在这里插入图片描述

data1 = np.random.normal(133.35,0.13,10000)
data2 = np.random.normal(133.5,0.13,10000)
bins = np.arange(132,134,0.01)
# print(data)
plt.xlim([min(data1)-0.1*(max(data2)-min(data1)),max(data2)+0.1*(max(data2)-min(data1))])
plt.hist(data1,bins=bins,label='hist1',alpha=0.3)
plt.hist(data2,bins=bins,label='hist2',alpha=0.3)
plt.legend()
plt.show()

在这里插入图片描述

  • Legend
fig = plt.figure()
ax = plt.subplot(111)
x = np.arange(10)
for i in range(1,5):
    plt.plot(x,i*x**2,label = 'Line %s'%i)
# plt.legend(loc='center left')
plt.legend(loc='best')
ax.legend(loc='upper center',bbox_to_anchor = (0.5,1.15),ncol =4)

plt.show()

在这里插入图片描述

  • 散点图
x_coords = np.round(np.random.randn(10),2)
y_coords = np.round(np.random.randn(10),2)

plt.figure(figsize=(10,8))
plt.scatter(x_coords,y_coords,marker='s',s=50)

for x,y in zip(x_coords,y_coords):
    plt.annotate('(%s,%s)'%(x,y),xy=(x,y),xytext=(0,-15),textcoords = 'offset points',ha ='center')

plt.show()

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这么神奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值