python画图

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

画图只能用第三方的包:
直接显示: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'] 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值