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.
相关推荐
时来天地皆同力.1 小时前
Java面试基础:概念
java·开发语言·jvm
豌豆花下猫1 小时前
让 Python 代码飙升330倍:从入门到精通的四种性能优化实践
后端·python·ai
夏末蝉未鸣011 小时前
python transformers库笔记(BertForTokenClassification类)
python·自然语言处理·transformer
hackchen1 小时前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang
铲子Zzz3 小时前
Java使用接口AES进行加密+微信小程序接收解密
java·开发语言·微信小程序
小小小新人121233 小时前
C语言 ATM (4)
c语言·开发语言·算法
Two_brushes.3 小时前
【linux网络】网络编程全流程详解:从套接字基础到 UDP/TCP 通信实战
linux·开发语言·网络·tcp/udp
weixin_418813873 小时前
Python-可视化学习笔记
笔记·python·学习
小白学大数据3 小时前
R语言爬虫实战:如何爬取分页链接并批量保存
开发语言·爬虫·信息可视化·r语言
争不过朝夕,又念着往昔3 小时前
Go语言反射机制详解
开发语言·后端·golang