当前位置: 首页 > news >正文

python绘图(pandas)

matplotlib绘图

import pandas as pd 
abs_path = r'F:\Python\learn\python附件\pythonCsv\data.csv'
df = pd.read_csv(abs_path, encoding='gbk')
# apply根据多列生成新的一个列的操作,用apply
df['new_score'] = df.apply(lambda x : x.数学 + x.语文, axis=1)# 最后几行
df.tail(2)
序号姓名性别语文数学英语物理化学生物new_score
56李四808080808080160
67王五707070707070140
df = df.drop(['new_score'],axis=1)
df.head()
序号姓名性别语文数学英语物理化学生物
01渠敬辉806030403060
12韩辉909575758085
23韩文晴958085608090
34石天洋909095807580
45张三606060606060

绘图

import numpy as np
import matplotlib.pyplot as plt%matplotlib inline
# 上一行是必不可少的,不加这一行就不会显示到notebook之中
---------------------------------------------------------------------------ModuleNotFoundError                       Traceback (most recent call last)<ipython-input-11-e41dd406839b> in <module>1 import numpy as np
----> 2 import matplotlib.pyplot as plt3 4 get_ipython().run_line_magic('matplotlib', 'inline')5 # 上一行是必不可少的,不加这一行就不会显示到notebook之中G:\Anaconda\lib\site-packages\matplotlib\pyplot.py in <module>30 from cycler import cycler31 import matplotlib
---> 32 import matplotlib.colorbar33 import matplotlib.image34 from matplotlib import rcsetup, styleG:\Anaconda\lib\site-packages\matplotlib\colorbar.py in <module>25 26 import matplotlib as mpl
---> 27 import matplotlib.artist as martist28 import matplotlib.cbook as cbook29 import matplotlib.collections as collectionsModuleNotFoundError: No module named 'matplotlib.artist'
x = np.linspace(1,10,100)
y = np.sin(x)plt.plot(x,y)
plt.plot(x,np.cos(x))
[<matplotlib.lines.Line2D at 0x23236b74ec8>]

在这里插入图片描述

plt.plot(x,y,'--')
[<matplotlib.lines.Line2D at 0x23236c26108>]

在这里插入图片描述

fig = plt.figure()
plt.plot(x,y,'--')
[<matplotlib.lines.Line2D at 0x23236c9bac8>]

在这里插入图片描述

fig.savefig('F:/Python/learn/python附件/python图片/first_figure.png')
# 虚线样式
plt.subplot(2,1,2)
plt.plot(x,np.sin(x),'--')plt.subplot(2,1,1)
plt.plot(x,np.cos(x))
[<matplotlib.lines.Line2D at 0x23236e1bec8>]

在这里插入图片描述

# 点状样式
x = np.linspace(0,10,20)
plt.plot(x,np.sin(x),'o')
[<matplotlib.lines.Line2D at 0x23236f99048>]

在这里插入图片描述

# color控制颜色
x = np.linspace(0,10,20)
plt.plot(x,np.sin(x),'o',color='red')
[<matplotlib.lines.Line2D at 0x23237147188>]

在这里插入图片描述

# 加label
x = np.linspace(0,10,100)
y = np.sin(x)plt.plot(x,y,'--',label='sin(x)')
plt.plot(x,np.cos(x),'o',label='cos(x)')
# legend控制label的显示效果,loc是控制label的位置的显示
plt.legend(loc='upper right')
<matplotlib.legend.Legend at 0x23238463848>

在这里插入图片描述

plt.legend?
# 当遇到一个不熟悉的函数的时候,多使用?号,查看函数的文档
#plot函数,可定制的参数非常多
x = np.linspace(0,10,20)
y = np.sin(x)
plt.plot(x,y,'-d',color='orange',markersize=16,linewidth=2,markeredgecolor='gray',markeredgewidth=1)
(-0.5, 1.2)

在这里插入图片描述

# 具体参数可查看文档
plt.plot?
# ylim xlim 限定范围
plt.plot(x,y,'-d',color='orange',markersize=16,linewidth=2,markeredgecolor='gray',markeredgewidth=1)
plt.ylim(-0.5,1.2)
plt.xlim(2,8)
(2, 8)

在这里插入图片描述

# 散点图
plt.scatter(x,y,s=100, c='gray')
<matplotlib.collections.PathCollection at 0x23239ef89c8>

在这里插入图片描述

plt.style.use('seaborn-whitegrid')x = np.random.randn(100)
y = np.random.randn(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
plt.scatter(x,y,c=colors,s=sizes,alpha=0.4)
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x23239c7f948>

在这里插入图片描述

pandas本身自带绘图

线型图

df = pd.DataFrame(np.random.rand(100,4).cumsum(0),columns=['A','B','C','D'])
df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x2323c0c8bc8>

在这里插入图片描述

df.A.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x2323c15e648>

在这里插入图片描述

柱状图

df = pd.DataFrame(np.random.randint(10,50,(3,4)),columns=['A','B','C','D'],index=['one','two','three'])
df.plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x2323c93ea88>

在这里插入图片描述

# df.B.plot.bar()
# 等价于上面的绘制
df.plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot at 0x2323c75e348>

在这里插入图片描述

df.plot(kind='bar',stacked=True)
<matplotlib.axes._subplots.AxesSubplot at 0x2323c86e648>

在这里插入图片描述

直方图

df = pd.DataFrame(np.random.randn(100,4),columns=['A','B','C','D'])
df.hist(column='A',figsize=(5,4))
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000002323EB7DFC8>]],dtype=object)

在这里插入图片描述

密度图

df.plot.kde() # df.plot(kind='kde')
<matplotlib.axes._subplots.AxesSubplot at 0x2323cd84808>

在这里插入图片描述

3D图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as npfig = plt.figure()
ax = fig.gca(projection='3d')# Make data
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)#Plot the surface
surf = ax.plot_surface(X,Y,Z,cmap=cm.coolwarm,linewidth=0,antialiased=False)# Customize the z axis
ax.set_zlim(-1.01,1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))#Add a colcr bar which maps values to colors
fig.colorbar(surf, shrink=0.5, aspect=5)plt.show()
G:\Anaconda\lib\site-packages\ipykernel_launcher.py:8: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().

在这里插入图片描述

#再画一个利用coolwarm类型的图
import pylab as plt
import numpy as np
#数据处理
X=np.linspace(-6,6,1000)
Y=np.linspace(-6,6,1000)
X,Y=np.meshgrid(X,Y)
#设置绘图
#推荐plt.axes的写法,不容易出现图像显示空白的情况
ax=plt.axes(projection="3d")Z=np.sin(np.sqrt(X*X+Y*Y))surf=ax.plot_surface(X,Y,Z,cmap="coolwarm")
plt.colorbar(surf)
ax.set_xlabel("X",color='r')
ax.set_ylabel("Y",color='r')
plt.title("3D CoolWarm Surface", fontsize=10)
plt.savefig('F:/Python/learn/python附件/python图片/first_figure.png', dpi=500, bbox_inches='tight')
plt.show()

在这里插入图片描述

3D绘图实例

# 第一步 import导包import numpy as np
import matplotlib as mpl
from matplotlib import cm
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 第二步 水平和垂直平面# 创建画布
fig = plt.figure(figsize=(12, 8),facecolor='lightyellow')# 创建 3D 坐标系
ax = fig.gca(fc='whitesmoke',projection='3d' )# 二元函数定义域平面
x = np.linspace(0, 9, 9)
y = np.linspace(0, 9, 9)
X, Y = np.meshgrid(x, y)# -------------------------------- 绘制 3D 图形 --------------------------------
# 平面 z=4.5 的部分
ax.plot_surface(X,Y,Z=X*0+4.5,color='g',alpha=0.6) # 平面 y=4.5 的部分
ax.plot_surface(X,Y=X*0+4.5,Z=Y,color='y',alpha=0.6)  # 平面 x=4.5 的部分
ax.plot_surface(X=X*0+4.5,Y=Y,Z=X, color='r',alpha=0.6)    
# --------------------------------  --------------------------------
# 设置坐标轴标题和刻度
ax.set(xlabel='X',ylabel='Y',zlabel='Z',xlim=(0, 9),ylim=(0, 9),zlim=(0, 9),xticks=np.arange(0, 10, 2),yticks=np.arange(0, 10, 1),zticks=np.arange(0, 10, 1))# 调整视角
ax.view_init(elev=15,    # 仰角azim=60   # 方位角)# 显示图形
plt.show()
G:\Anaconda\lib\site-packages\ipykernel_launcher.py:16: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().app.launch_new_instance()

在这里插入图片描述

# 第三步 斜平面# 创建画布
fig = plt.figure(figsize=(12, 8),facecolor='lightyellow')# 创建 3D 坐标系
ax = fig.gca(fc='whitesmoke',projection='3d' )# 二元函数定义域
x = np.linspace(0, 9, 9)
y = np.linspace(0, 9, 9)
X, Y = np.meshgrid(x, y)# -------------------------------- 绘制 3D 图形 --------------------------------
# 平面 z=3 的部分
ax.plot_surface(X,Y,Z=X*0+3,color='g')
# 平面 z=2y 的部分
ax.plot_surface(X,Y=Y,Z=Y*2,color='y',alpha=0.6)
# 平面 z=-2y + 10 部分
ax.plot_surface(X=X,Y=Y,Z=-Y*2+10,color='r',alpha=0.7)
# --------------------------------  --------------------------------# 设置坐标轴标题和刻度
ax.set(xlabel='X',ylabel='Y',zlabel='Z',xlim=(0, 9),ylim=(0, 9),zlim=(0, 9),xticks=np.arange(0, 10, 2),yticks=np.arange(0, 10, 1),zticks=np.arange(0, 10, 1))# 调整视角
ax.view_init(elev=15,    # 仰角azim=10   # 方位角)# 显示图形
plt.show()
G:\Anaconda\lib\site-packages\ipykernel_launcher.py:10: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().# Remove the CWD from sys.path while we load stuff.

在这里插入图片描述

http://www.lryc.cn/news/341909.html

相关文章:

  • Android(Java)项目支持Kotlin语言开发
  • Terraform创建模块
  • 《华为鸿蒙:从备胎到主角的崛起之路》
  • FPGA学习笔记(2)——Verilog语法及ModelSim使用
  • 2024年十大AI工具,让你的工作学习效率飞跃
  • linux之NAMP
  • uniapp 禁止截屏(应用内,保护隐私)插件 Ba-ScreenShot
  • 数字电路-5路呼叫显示电路和8路抢答器电路
  • C++中的函数签名
  • Mac brew安装Redis之后更新配置文件的方法
  • 安卓应用开发(一):工具与环境
  • 基于springboot+vue+Mysql的在线动漫信息平台
  • C++设计模式-结构型设计模式
  • open-webui+ollama本地部署Llama3
  • 个人对行为型设计模式的理解 @by_TWJ
  • 苹果挖走大量谷歌人才,建立神秘人工智能实验室;李飞飞创业成立「空间智能」公司丨 RTE 开发者日报 Vol.197
  • 行业唯一!易保全牵头编制的《区块链数据访问安全技术通则》发布
  • Rust Rocket创建第一个hello world的Web程序 Rust Rocket开发常用网址和Rust常用命令
  • 第G9周:ACGAN理论与实战
  • Linux网络部分——DNS域名解析服务
  • 预处理详解
  • Python的创建和使用自定义模块
  • Python根据预设txt生成“你画我猜”题目PPT(素拓活动小工具)
  • 小程序地理位置接口权限直接抄作业
  • 【Osek网络管理测试】[TG3_TC6]等待总线睡眠状态_2
  • BEV下统一的多传感器融合框架 - FUTR3D
  • c#和python的flask接口的交互
  • Python测试框架Pytest的参数化详解
  • KernelSU 如何不通过模块,直接修改系统分区
  • 红日靶场ATTCK 1通关攻略