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 | |
---|---|---|---|---|---|---|---|---|---|---|
5 | 6 | 李四 | 女 | 80 | 80 | 80 | 80 | 80 | 80 | 160 |
6 | 7 | 王五 | 男 | 70 | 70 | 70 | 70 | 70 | 70 | 140 |
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 |
绘图
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.