python绘图(pandas)

matplotlib绘图

python 复制代码
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 |
| 5 | 6 | 李四 | 女 | 80 | 80 | 80 | 80 | 80 | 80 | 160 |

6 7 王五 男 70 70 70 70 70 70 140
python 复制代码
df = df.drop(['new_score'],axis=1)
df.head()

| | 序号 | 姓名 | 性别 | 语文 | 数学 | 英语 | 物理 | 化学 | 生物 |
| 0 | 1 | 渠敬辉 | 男 | 80 | 60 | 30 | 40 | 30 | 60 |
| 1 | 2 | 韩辉 | 男 | 90 | 95 | 75 | 75 | 80 | 85 |
| 2 | 3 | 韩文晴 | 女 | 95 | 80 | 85 | 60 | 80 | 90 |
| 3 | 4 | 石天洋 | 男 | 90 | 90 | 95 | 80 | 75 | 80 |

4 5 张三 男 60 60 60 60 60 60

绘图

python 复制代码
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 plt
      3 
      4 get_ipython().run_line_magic('matplotlib', 'inline')
      5 # 上一行是必不可少的,不加这一行就不会显示到notebook之中


G:\Anaconda\lib\site-packages\matplotlib\pyplot.py in <module>
     30 from cycler import cycler
     31 import matplotlib
---> 32 import matplotlib.colorbar
     33 import matplotlib.image
     34 from matplotlib import rcsetup, style


G:\Anaconda\lib\site-packages\matplotlib\colorbar.py in <module>
     25 
     26 import matplotlib as mpl
---> 27 import matplotlib.artist as martist
     28 import matplotlib.cbook as cbook
     29 import matplotlib.collections as collections


ModuleNotFoundError: No module named 'matplotlib.artist'
python 复制代码
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>]
python 复制代码
plt.plot(x,y,'--')
复制代码
[<matplotlib.lines.Line2D at 0x23236c26108>]
python 复制代码
fig = plt.figure()
plt.plot(x,y,'--')
复制代码
[<matplotlib.lines.Line2D at 0x23236c9bac8>]
python 复制代码
fig.savefig('F:/Python/learn/python附件/python图片/first_figure.png')
python 复制代码
# 虚线样式
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>]
python 复制代码
# 点状样式
x = np.linspace(0,10,20)
plt.plot(x,np.sin(x),'o')
复制代码
[<matplotlib.lines.Line2D at 0x23236f99048>]
python 复制代码
# color控制颜色
x = np.linspace(0,10,20)
plt.plot(x,np.sin(x),'o',color='red')
复制代码
[<matplotlib.lines.Line2D at 0x23237147188>]
python 复制代码
# 加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>
python 复制代码
plt.legend?
# 当遇到一个不熟悉的函数的时候,多使用?号,查看函数的文档
python 复制代码
#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)
python 复制代码
# 具体参数可查看文档
plt.plot?
python 复制代码
# 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)
python 复制代码
# 散点图
plt.scatter(x,y,s=100, c='gray')
复制代码
<matplotlib.collections.PathCollection at 0x23239ef89c8>
python 复制代码
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本身自带绘图

线型图

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

】

python 复制代码
df.A.plot()
复制代码
<matplotlib.axes._subplots.AxesSubplot at 0x2323c15e648>

】

柱状图

python 复制代码
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>
python 复制代码
# df.B.plot.bar()
python 复制代码
# 等价于上面的绘制
df.plot(kind='bar')
复制代码
<matplotlib.axes._subplots.AxesSubplot at 0x2323c75e348>
python 复制代码
df.plot(kind='bar',stacked=True)
复制代码
<matplotlib.axes._subplots.AxesSubplot at 0x2323c86e648>

直方图

python 复制代码
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)

密度图

python 复制代码
df.plot.kde() # df.plot(kind='kde')
复制代码
<matplotlib.axes._subplots.AxesSubplot at 0x2323cd84808>

3D图

python 复制代码
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = 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().
python 复制代码
#再画一个利用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绘图实例

python 复制代码
# 第一步 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
python 复制代码
# 第二步 水平和垂直平面

# 创建画布
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()
python 复制代码
# 第三步 斜平面

# 创建画布
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.
相关推荐
BD_Marathon几秒前
多轮对话聊天机器人
开发语言·机器人·c#
泡茶喝茶写代码几秒前
A股量化数据工程:从 REST 接口到策略信号(第 1 篇):指数列表与实时行情接入
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据接口
Sarvartha6 分钟前
接口基础知识
java·开发语言
happylifetree24 分钟前
Python34-35:核心语法-流程控制语句-循环-综合案例
python
沐晓时光30 分钟前
C语言入门,深入理解指针(1)
c语言·开发语言
AC赳赳老秦32 分钟前
OpenClaw 数据引用规范自动生成:为公开数据构建可信来源标注与标准引用体系
大数据·开发语言·汇编·数据库·人工智能·deepseek·openclaw
吃饱了得干活38 分钟前
Agent 的记忆与工具:从上下文窗口到 MCP
python·agent·mcp
无忧.芙桃40 分钟前
C++语言原理与实践(十):vector类的底层实现
开发语言·c++·算法
燐妤1 小时前
LangGraph-复习总览
python·ai·面试·agent·学习方法·langgraph
尹人入圣1 小时前
市面上IP驱动产业新场景新工具
运维·网络·python·tcp/ip