python画图

本文介绍了Python中的数据可视化工具matplotlib和seaborn的使用,包括单图的绘制,如图例、轴的设置,多图处理,三维图的创建,颜色表的应用,以及图片的保存。此外,还提到了pandas和seaborn在数据可视化的辅助作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

画图只能用第三方的包:
直接显示:matplotlib,seaborn(更美观,但是需要和matplotlib结合使用),plotly
界面:pyqt,pyqtgraph 更多的是用来绘制GUI
html: pyecharts
功能很单一,调用matplotlib:pandas

matplotlib

绘图API:pyplot
集成API:pylab 是matplotlib,scipy, numpy的集成库

单图

可以分为plot(线图),scatter(散点),bar(直方图),pie,hist,

import matplotlib.pyplot as plt
plt.rcParams['font.family']='SimHei' # 设置字体,一定要在plt.plot之前
plt.plot(x,y,color='r',linewidth=1.0,linestyle='_',label='label')
plt.scatter(x,y)
plt.bar(x,y,facecolor='r',edgecolor='white)

plt.pie(x=[15,30.55,44.44,10], labels=['a','b','c','d'], explode=[0,0.1,0,0],autopct='%3.1f %%',
 shadow=True, labeldistance=1.1, startangle = 90,pctdistance = 0.6)#explode代表哪块是凸出来
 
plt.hist(data,bins=100,normed=True)#data是一个list

X,Y=np.meshgrid(x,y)
plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='jet')#filled contour
plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5) #线
图例(legend)
plt.lengend(loc='upper left') #当plot中有lable时,推荐这种,如果改变了线段的条数会自动修改
plt.lengend([])#list中是要添加的图例
plt.xlim(min_x,max_x) #轴的范围
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
   [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'],rotation=90) #在轴的指定位置显示指定的字符

from matplotlib.ticker import MultipleLocator, FormatStrFormatter 
xmajorLocator   = MultipleLocator(20) #将x主刻度标签设置为20的倍数  
xmajorFormatter = FormatStrFormatter('%1.1f') #设置x轴标签文本的格式   
ax.xaxis.set_major_locator(xmajorLocator)  
ax.xaxis.set_major_formatter(xmajorFormatter) 

from matplotlib.dates import AutoDateLocator, DateFormatter  
autodates = AutoDateLocator()  
yearsFmt = DateFormatter('%Y-%m-%d %H:%M:%S')    
ax.xaxis.set_major_locator(autodates)  
ax.xaxis.set_major_formatter(yearsFmt)#如果用datetime不行的话,将时间通过matplotlib.dates.date2num转换下

ax.tick_params(axis='y', colors=color) #设置刻度的颜色
ax.spines['left'].set_color(color) #设置轴的颜色

plt.gcf().autofmt_xdate() #自动设置轴的显示

一般有四个轴,为了将轴搬到中间,需要将两个弄成无色,另外两个移动位置到原点,当然也可以是其他位置

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')#刻度在下
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')#刻度在左
ax.spines['left'].set_position(('data',0))

多图

plt.figure()#定义figure,里面可以加尺寸之类的

# figure分成3行3列, 取得第一个子图的句柄, 第一个子图跨度为1行3列, 起点是表格(0, 0),其他类推
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan = 3, rowspan = 1)

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, 0:2]) #第二行,第一二列,前闭后开

fig, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex = True, sharey = True)#这个很简单了

避免多图重叠

plt.tight_layout()

三维图(contourf 3d)

contourf

ax = plt.subplot(1,1,1)
# cset = ax.contourf(p0_mesh, phi_mesh, den_mesh, levels=levels, cmap='rainbow', norm=LogNorm())
cset = ax.contourf(p0_mesh, phi_mesh, den_mesh, locator=ticker.LogLocator(subs=(1.0,)), cmap='rainbow')
plt.colorbar(cset, ax=ax, label='density')

plot_surface

ax = plt.subplot(1,1,1, projection='3d')
surf = ax.plot_surface(p0_mesh, phi_mesh, np.nan_to_num(den_mesh, 0.001), cmap='rainbow')
plt.colorbar(surf)

颜色表

https://matplotlib.org/examples/color/colormaps_reference.html

图片的保存

plt.savefig(file,dpi=600)#可以通过file扩展名来改变类型,eps,png...
plt.show()

先savefig然后show否则可能是空白,当然还有其他方法,但是感觉这个最简单

示例

import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
from datetime import datetime

local_path = os.path.dirname(os.path.abspath(__file__)) + os.sep
#--------------------------------------------------------read data
df = pd.read_csv(local_path+'para.csv', sep=',')
df['time'] = date2num([datetime.strptime(d, '%Y-%m-%d/%H:%M:%S') for d in df['start_time']])
# xs = [datetime.strptime(d, '%Y-%m-%d/%H:%M:%S').date() for d in df['start_time']]
#--------------------------------------------------------- plot 
fig = plt.figure(figsize=(6,8))

ax1 = plt.subplot(4,1,1)
ax1.plot(df['rot_no'], df['ssn'], 'k', scalex=True)
ax1.set_xlim(min(df['rot_no']), max(df['rot_no']))
ax1.set_ylabel('Sunspot Number')
ax11 = ax1.twiny()
ax11.plot_date(df['time'], df['ssn'], 'k-', scalex=True)
ax11.set_xlim(min(df['time']), max(df['time']))
ax11.set_xlabel('Year')

ax2 = plt.subplot(4,1,2, sharex=ax1)
ax2.plot(df['rot_no'], df['L_av'],'k', label='L_av')
ax2.plot(df['rot_no'], df['R_av'], 'r--', label='R_av')
ax2.legend(loc='upper right', fontsize='x-small')
ax2.set_ylabel('Tilt Angle (degree)')

ax3 = plt.subplot(4,1,3, sharex=ax1)
ax3.plot(df['rot_no'], df['mag_n'], 'k', label='North Pole')
ax3.plot(df['rot_no'], df['mag_s'], 'r--', label='South Pole')
ax3.legend(loc='upper right', fontsize='x-small')
ax3.axhline(0, c='b')
ax3.set_ylabel('Polar Field (G)')

ax4 = plt.subplot(4,1,4, sharex=ax1)
ax4.plot(df['rot_no'], df['pp'], 'k')
ax4.set_ylabel('Percentage A > 0')
ax4.set_xlabel('Carrington Rotation')

plt.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=0.15,hspace=0.05)
fig.savefig(local_path+'para_sun.png', dpi=600)

#-----------------------------------------------------pic2
fig2 = plt.figure(figsize=(6,8))

ax1 = plt.subplot(5,1,1)
ax1.plot(df['rot_no'], df['ssn'], 'k')
ax1.set_xlim(min(df['rot_no']), max(df['rot_no']))
ax1.set_ylabel('Sunspot Number')
ax1.set_xlabel('Carrington Rotation')
ax11 = ax1.twiny()
ax11.plot_date(df['time'], df['ssn'], 'k-')
ax11.set_xlim(min(df['time']), max(df['time']))
ax11.set_xlabel('Year')

ax2 = plt.subplot(5,1,2, sharex=ax1)
ax2.plot(df['rot_no'], df['v_avg'], 'k')
ax2.set_ylabel('Vsw (km/s)')

ax3 = plt.subplot(5,1,3, sharex=ax1)
ax3.plot(df['rot_no'], df['p400'], 'b', label='V > 400')
ax3.plot(df['rot_no'], df['p500'], 'g', label='V > 500')
ax3.plot(df['rot_no'], df['p600'], 'r', label='V > 600')
ax3.legend(loc='upper right', fontsize='x-small')
ax3.set_ylabel('Percentage')

ax4 = plt.subplot(5,1,4, sharex=ax1)
ax4.plot(df['rot_no'], df['b_avg'], 'k')
ax4.set_ylabel('HMF (nT)')

ax5 = plt.subplot(5,1,5, sharex=ax1)
ax5.plot(df['rot_no'], df['b_std'], 'k')
ax5.set_ylabel('$\delta B (nT)$')
ax5.set_xlabel('Carrington Rotation')

plt.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=0.15,hspace=0.05)
fig2.savefig(local_path+'para_sw.png', dpi=600)
# ----------------------------
# plt.show()

pandas

df.plot(kind='bar') # 直方图 kind='barh' 水平直方图
df.plot(kind='kde') # 核密度估计曲线
plt.show() # 因为使用的是matplotlib,所以必须加上这句

seaborn

import matplotlib.pyplot as plt
import seaborn as sns
sns.set() # sns.set_style('darkgrid') 
plt.plot(x,y)
plt.legend('abcdef',ncol=2,loc='') 

sns.kdeplot(x,shade=True) # 核密度曲线
sns.distplot(a) # 直方图+核密度曲线
sns.pairplot(a) #散点图矩阵
sns.jointplot(x,y,kind='reg') # 联合分布图
sns.stripplot(data=df,x='rank',y='salary',jitter=True,alpha=0.5) #散点图
sns.boxplot(data=d,x='rank',y='salary') # 箱线图

for x in ['height','weight']:
	plt.hist(df[x],normed=True,alpha=0.5)  # 多个hist放到一起
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值