python学习5-matplotlib

python学习5-matplotlib

下面的内容是根据李老师在B站上的课程总结的,主要用于自己复习回顾
这一篇是接着上一篇《python学习4-Numpy等》的
62、数据可视化-折线图和散点图

#折线图和散点图

#画折线图时要引入一系列的x和y
%matplotlib inline
import matplotlib.pyplot as plt
days = list(range(0,22,3))
print("生成x轴的数轴:",days)
#生成y轴的数轴
celsius_values = [25.6,24.1,26.7,28.3,27.5,30.5,32.8,33.1] #y值
plt.plot(days,celsius_values) #画成折线图
plt.show() #显示图象
plt.plot(days,celsius_values,'bo') #散点图,b表示颜色,o表示小点
plt.show() #显示图象

结果:
在这里插入图片描述
63、绘制多个数据

#绘制多个数据
%matplotlib inline
import matplotlib.pyplot as plt
days = list(range(1,9))
celsius_min = [19.6,24.1,26.7,28.3,27.5,30.5,32.8,33.1]
celsius_max = [24.8,28.9,31.3,33.0,34.9,35.6,38.4,39.2]
fig,ax = plt.subplots()  #ax是figure的子部分
ax.set(xlabel = 'Day',ylabel = 'Temperature in Celsius',title = 'Temperature Graph')
ax.plot(days,celsius_min) #折线图
ax.plot(days,celsius_min,"oy") #散点图
ax.plot(days,celsius_max)#折线图
ax.plot(days,celsius_max,'or')#散点图
#将折线图和散点图叠合
plt.show()
#fig.savefig("filename.png") 保存图表到一个文件

在这里插入图片描述
画多条图线

#画多条图线
import numpy as np
X = np.linspace(0, 2*np.pi, 50, endpoint=True)
F1,F2,F3,F4 = 3*np.sin(X),np.sin(2*X),0.3*np.sin(X),np.cos(X)
fig,ax = plt.subplots()  
#subplots函数有两个返回值,一个是figure,一个是axes,fig即figure,ax即axes。 axes是figure的子部分,但真正画图是画在axes上的 
ax.plot(X,F1,color="blue",linewidth=2.5,linestyle="-")  #指定线的颜色、宽度、线形
ax.plot(X,F2,color="red",linewidth=1.5,linestyle="--")
ax.plot(X,F3,color="green",linewidth=2,linestyle=":")
ax.plot(X,F4,color="grey",linewidth=2,linestyle="-.")
plt.show()

在这里插入图片描述
图案填充:可以在两个曲线之间进行阴影填充

#图案填充:可以在两个曲线之间进行阴影填充
#fill_between(x,y1,y2,where = None,interpolate=False,**kwargs) 在y1和y2之间填充,kwargs是关键字列表,例如alpha是不透明
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
fig,ax = plt.subplots()
ax.plot(X,Y,color='blue',alpha = 1.00)
ax.fill_between(X,0,Y,color='blue',alpha=0.4)  #即Y1=0,Y2=sin(2*x)
plt.show()

在这里插入图片描述
64、matplotlib绘图的基本步骤:
数据准备——>plt.subplots()准备图形环境——>ax.pilot()绘图,增加参数修改显示效果——>美化图形,title、label等——>plt.show()显示图形

绘制多子图:
subplots函数创建了一个figure以及一系列子图,创建子图的通用布局
subplot(nrow1=1,ncols=1,sharex=False,sharey=False,squeeze=True,subplot_kw=None,gridspec_kw=None,**fig_kw)
该函数返回一个figure以及一个axes对象或者一组axes对象。nrows和ncols表示行数和列数,nrows=2.ncols=3表示两行三列
sharex和sharey表示x轴和y轴是否共享

import matplotlib.pyplot as plt
plt.figure(figsize=(6,4)) #创建环境,宽6高4
rows,cols = 2,3 #两行三列
fig,ax = plt.subplots(rows,cols,sharex='col',sharey='row') #共享x轴和y轴,返回的ax实际上是6个axes的列表
for row in range(2):
    for col in range(3):
        #参数‘ha’表示horizontal alignment,即水平对齐
        ax[row,col].text(0.5,0.5,str((row,col)),color="green",fontsize=18,ha='center') #简单的绘制文本
plt.show()

在这里插入图片描述

import numpy as np
x = np.linspace(0,2*np.pi,400)
y = np.sin(x**2) + np.cos(x)
derivative = 2*x*np.cos(x**2)-np.sin(x) #导数
f,(ax1,ax2) = plt.subplots(1,2,sharey = True) #共享Y轴
ax1.plot(x,y)
ax1.set_title("sharing Y axis")
ax2.plot(x,derivative)
plt.show()

在这里插入图片描述

#设置极坐标
fig,axes = plt.subplots(2,2,subplot_kw=dict(polar=True))  #两行两列,subplot_kw=dict(polar=True)控制画出极坐标
axes[0,0].plot(x,y)
axes[0,1].plot(x,np.sin(x**2)+np.cos(x**3))
axes[1,0].plot(x,np.cos(x)*np.sin(x**2))
axes[1,1].plot(x,2*x*np.cos(x**2)-np.sin(x),"g--")
plt.show()

在这里插入图片描述
65、
柱状图

#柱状图
import matplotlib.pyplot as plt
import numpy as np
gaussian_numbers = np.random.normal(size = 10000) #正态分布  给10000个数值
n,bins,patches = plt.hist(gaussian_numbers)  #hist函数生成柱状图
#n指每个范围包含多少个,bins是每个柱子的范围,patches是指柱子的图形、横纵坐标等信息
plt.title("Gaussian Histogram") 
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
print("n:",n,"   The sum of n:",sum(n))
print("bins:",bins)
print("patches:",patches)
print(patches[0])

在这里插入图片描述

#hist函数有许多参数,可以美化柱状图
plt.hist(gaussian_numbers,bins=100,density=True,stacked=True,edgecolor="#6A9662",color="#DDFFDD")
#bins=100是有100个柱子,edgecolor轮廓线
plt.show()

在这里插入图片描述

#条形图:长方形的宽度没有任何数学含义
#竖向
bars1 = plt.bar([1,2,3,4],[1,4,9,16])
bars1[3].set_color('green') #仅设定第四栏的颜色
plt.show()
#横向
bars2 = plt.barh([1,2,3,4],[1,4,9,16])
bars2[3].set_color('green') #仅设定第四栏的颜色
plt.show()

在这里插入图片描述
在这里插入图片描述

#多列条形图
# import matplotlib.pyplot as plt
# import numpy as np
last_week_cups=(20,35,30,35,27) #纵坐标
this_week_cups=(25,32,34,20,25)
names = ['Mary','Paul','Billy','Franka','Stephan'] #横坐标上的

fig = plt.figure(figsize=(6,5),dpi=200) 
ax = fig.add_axes([0.1,0.3,0.8,0.6]) 

width = 0.35
ticks = np.arange(len(names))
ax.bar(ticks,last_week_cups,width,label='Last week')
ax.bar(ticks+width,this_week_cups,width,align="center",label='This week')

ax.set_ylabel('Cups of Coffee')
ax.set_title('Cofffee Consummation')
ax.set_xticks(ticks+width/2) #设置坐标轴刻度
ax.set_xticklabels(names) #设置刻度名称

ax.legend(loc='best') #对图例的优化,选择空白地方显示图例
plt.show()

在这里插入图片描述

#堆叠图:在纵向上发生了偏移
# import matplotlib.pyplot as plt
# import numpy as np
coffee = np.array([5,5,7,6,7])
tea = np.array([1,2,0,2,0])
water = np.array([10,12,14,12,15])
names = ['Mary','Paul','Billy','Franka','Stephan'] #横坐标上的

fig = plt.figure(figsize=(6,5),dpi=200)
left,bottom,width,height = 0.2,0.1,0.7,0.8
ax = fig.add_axes([left,bottom,width,height])

width = 0.35
ticks = np.arange(len(names))
ax.bar(ticks,tea,width,label="Coffee",bottom=water+coffee)
ax.bar(ticks,coffee,width,align="center",label="Tea",bottom=water)
ax.bar(ticks,water,width,align="center",label="Water")
plt.show()

在这里插入图片描述

#饼图
# import matplotlib.pyplot as plt
# import numpy as np
import matplotlib

matplotlib.rcParams['font.sans-serif']='SimHei' #改字体为黑体
languages = {"Java":0.16881,"C":0.14966,"C++":0.07471,"Python":0.06992,
            "Visual Basic":0.04762,"C#":0.03541,"PHP":0.02925,
            "JavaScript":0.02411,"SQl":0.02316,"Others":0.36326}
fig,ax = plt.subplots()
data = np.array(list(languages.values())).astype(float) #饼图显示数据,将其转换成float格式
explode = [0.1,0,0,0,0,0,0,0,0,0] #设置突出显示的内容,这里为突出显示第一项
#autopct为显示百分比
ax.pie(data,labels=languages.keys(),autopct='%.1f%%',explode=explode) #explode突出显示
ax.set_title("TIOBE 2018年8月的编程语言指数排行耪") #设置标题
ax.axis("equal")#设置x、y轴等长,否则图象将不是正源
plt.show()

在这里插入图片描述
66、等值线图:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(-3.0,3.0,30)  #将起点和终点分成指定的分数
ylist = np.linspace(-3.0,3.0,40)
X,Y=np.meshgrid(xlist,ylist)#画等值线图

fig,ax=plt.subplots()
ax.scatter(X,Y,color="green") #散点图
ax.set_title("Regular Grid,r=created by Meshgrid")
ax.set_xlabel('x')
ax.set_ylabel('y')
Z = np.sqrt(X**2+Y**2)
#print(Z)
fig = plt.figure(figsize=(6,5))
left,bottom,width,height = 0.1,0.1,0.8,0.8
ax = fig.add_axes([left,bottom,width,height])  #在原有的figure上边增加一个axes
cp=ax.contour(X,Y,Z)
ax.clabel(cp,inline=True,fontsize=10)
ax.set_title("Contour Piot")
ax.set_xlabel('x(cm)')
ax.set_ylabel('y(cm)')
plt.show()

在这里插入图片描述
在这里插入图片描述
66、1.24~1.31日新冠肺炎新增确诊病例折线图

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif']='SimHei' #设置字体为黑体
date = ['1月24','1月25','1月26','1月27','1月28','1月29','1月30','1月31','2月1','2月2','2月3','2月4','2月5','2月6','2月7',]
nation = [458,695,819,1763,1463,2058,1660,2059,2617,2849,3185,3865,3730,3107,3407]
others = [277,367,454,472,623,709,757,712,696,746,840,709,743,660,566]
fig,ax = plt.subplots(2,1,sharex = True)
ax[0].plot(date,nation)
ax[1].plot(date,others)
for i,label in enumerate(ax[1].get_xticklabels()): #控制日期的显示
    label.set_visible(i%3==0)

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值