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.
相关推荐
吾爱星辰43 分钟前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer44 分钟前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
FreakStudio1 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
IT良1 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
丶21361 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
Kalika0-02 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch2 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家2 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技2 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web2 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery