赞
踩
强烈推荐!!!!!!建议直接点赞收藏,方便接下来使用。
Matplotlib 是 Python 的绘图库。它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案,也可以和图形工具包一起使用。
虽然相比其他图形库(Seaborn | pyecharts | plotly | bokeh | pandas_profiling )这个库丑丑呆呆的,甚至有点难用,但人家毕竟是开山始祖,方法全,能够支持你各类骚操作的需求。可以说是现在python数据分析中,用的人最多的图形库了。
目录
4.用scatter方法画出x=(0,10)间sin的点图像
20.绘制垂直于x轴x<4 and x>6的参考区域,以及y轴y<0.2 and y>-0.2的参考区域
31.在一个1010的画布中,(0.65,0.65)的位置创建一个0.20.2的子图
37.显示一组二维数据的频度分布,并分别在x,y轴上,显示该维度的数据的频度分布
41.展示前5个宝可梦的Defense,Attack,HP的堆积条形图
43.展示前5个宝可梦的Defense,Attack,HP的堆积图
44.公用x轴,展示前5个宝可梦的Defense,Attack,HP的折线图
46.用scatter的x,y,c属性,展示所有宝可梦的Defense,Attack,HP数据
一、导入
In [ ]
- import matplotlib.pyplot as plt
- import numpy as np
In [ ]
- x = np.linspace(0, 10, 30)
- plt.plot(x, np.sin(x));
<matplotlib.figure.Figure at 0x21e8b022ef0>
其中:np.linkspace(0,10,30)是numpy中的一种方法,意思是 x轴的范围从0到10,绘制出来的函数总共平均取30个点导入相应的表达式中绘制出图像。
In [ ]
plt.plot(x, np.sin(x), '-o');
<matplotlib.figure.Figure at 0x21e8d1046d8>
In [ ]
plt.scatter(x, np.sin(x));
<matplotlib.figure.Figure at 0x21e8d104f98>
其中:我们从上面知道,plt.plot()f方法是用来画直线图的,而plt.scatter()用来画散点图。
In [ ]
- rng = np.random.RandomState(0)#rng(一个伪随机数生成器,即 np.random.RandomState() ),
- x = rng.randn(100)
- y = rng.randn(100)
- colors = rng.rand(100)
- sizes = 1000 * rng.rand(100)
-
- plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
- cmap='viridis')
- plt.colorbar(); # 展示色阶
具体来讲,randn是从标准正态分布中返回一个或多个样本值。正态分布,也即这些随机数的期望为0,方差为1;rand则会产生[0, 1)之间的随机数。
关于记忆方法,我们可以把randn中的n看成是正态分布(Normal distribution)中“Normal”的缩写。
<matplotlib.figure.Figure at 0x21e8d1e8780>
In [ ]
- x = np.linspace(0, 10, 50)
- dy = 0.8
- y = np.sin(x) + dy * np.random.randn(50)
-
- plt.errorbar(x, y, yerr=dy, fmt='.k')
<Container object of 3 artists>
<matplotlib.figure.Figure at 0x21e8d26a208>
In [ ]
- x = [1,2,3,4,5,6,7,8]
- y = [3,1,4,5,8,9,7,2]
- label=['A','B','C','D','E','F','G','H']
-
- plt.bar(x,y,tick_label = label);#plt.bar()方法用来画柱状图
<matplotlib.figure.Figure at 0x21e8d2d55c0>
In [ ]
plt.barh(x,y,tick_label = label);
<matplotlib.figure.Figure at 0x21e8d1bd0f0>
In [ ]
- data = np.random.randn(1000)
- plt.hist(data);
<matplotlib.figure.Figure at 0x21e8d39d400>
In [ ]
- plt.hist(data, bins=30,histtype='stepfilled', density=True)
- plt.show();
<matplotlib.figure.Figure at 0x21e8d3e2b38>
In [ ]
- x1 = np.random.normal(0, 0.8, 1000)
- x2 = np.random.normal(-2, 1, 1000)
- x3 = np.random.normal(3, 2, 1000)
-
- kwargs = dict(alpha=0.3, bins=40, density = True)
-
- plt.hist(x1, **kwargs);
- plt.hist(x2, **kwargs);
- plt.hist(x3, **kwargs);
<matplotlib.figure.Figure at 0x21e8d2255c0>
In [ ]
- mean = [0, 0]
- cov = [[1, 1], [1, 2]]
- x, y = np.random.multivariate_normal(mean, cov, 10000).T
- plt.hist2d(x, y, bins=30);
<matplotlib.figure.Figure at 0x21e8d1e0e80>
In [ ]
plt.hexbin(x, y, gridsize=30);
<matplotlib.figure.Figure at 0x21e8d3e29e8>
In [ ]
- x = np.linspace(0,10,100)
- plt.plot(x,np.sin(x),'--');
<matplotlib.figure.Figure at 0x21e8d3e2cc0>
In [ ]
- x = np.linspace(0,10,100)
- plt.plot(x, np.sin(x))
- plt.ylim(-1.5, 1.5);
<matplotlib.figure.Figure at 0x21e8e45e710>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y, label='sin(x)')
- plt.xlabel('variable x');
- plt.ylabel('value y');
<matplotlib.figure.Figure at 0x21e8e4c1358>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y, label='sin(x)')
- plt.title('三角函数');
<matplotlib.figure.Figure at 0x21e8e55eac8>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y)
- plt.grid()
<matplotlib.figure.Figure at 0x21e8e5974a8>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y)
- plt.axhline(y=0.8, ls='--', c='r')
<matplotlib.lines.Line2D at 0x21e8e614eb8>
<matplotlib.figure.Figure at 0x21e8e5f02b0>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y)
- plt.axvspan(xmin=4, xmax=6, facecolor='r', alpha=0.3) # 垂直x轴
- plt.axhspan(ymin=-0.2, ymax=0.2, facecolor='y', alpha=0.3); # 垂直y轴
<matplotlib.figure.Figure at 0x21e8e5f9780>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y)
- plt.text(3.2, 0, 'sin(x)', weight='bold', color='r');
<matplotlib.figure.Figure at 0x21e8d423cf8>
In [ ]
- x = np.linspace(0.05, 10, 100)
- y = np.sin(x)
- plt.plot(x, y)
- plt.annotate('maximum',xy=(np.pi/2, 1),xytext=(np.pi/2+1, 1),
- weight='bold',
- color='r',
- arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'));
<matplotlib.figure.Figure at 0x21e8e59c518>
In [ ]
- x = np.linspace(0, 10, 1000)
- fig, ax = plt.subplots()
-
- ax.plot(x, np.sin(x), label='sin')
- ax.plot(x, np.cos(x), '--', label='cos')
- ax.legend();
<matplotlib.figure.Figure at 0x21e8d22eb00>
In [ ]
- ax.legend(loc='upper left', frameon=False);
- fig
<matplotlib.figure.Figure at 0x21e8d22eb00>
In [ ]
- ax.legend(frameon=False, loc='lower center', ncol=2)
- fig
<matplotlib.figure.Figure at 0x21e8d22eb00>
In [ ]
- y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
- lines = plt.plot(x, y)
-
- # lines 是 plt.Line2D 类型的实例的列表
-
- plt.legend(lines[:2], ['first', 'second']);
-
- # 第二个方法
- #plt.plot(x, y[:, 0], label='first')
- #plt.plot(x, y[:, 1], label='second')
- #plt.plot(x, y[:, 2:])
- #plt.legend(framealpha=1, frameon=True);
<matplotlib.figure.Figure at 0x21e8e5d6da0>
In [ ]
- fig, ax = plt.subplots()
-
- lines = []
- styles = ['-', '--', '-.', ':']
- x = np.linspace(0, 10, 1000)
-
- for i in range(4):
- lines += ax.plot(x, np.sin(x - i * np.pi / 2),styles[i], color='black')
- ax.axis('equal')
(-0.5, 10.5, -1.1, 1.1)
<matplotlib.figure.Figure at 0x21e8d0c6048>
In [ ]
- # 设置第一组标签
- ax.legend(lines[:2], ['line A', 'line B'],
- loc='upper right', frameon=False)
-
- # 创建第二组标签
- from matplotlib.legend import Legend
- leg = Legend(ax, lines[2:], ['line C', 'line D'],
- loc='lower right', frameon=False)
- ax.add_artist(leg);
In [ ]
- x = np.linspace(0, 10, 1000)
- I = np.sin(x) * np.cos(x[:, np.newaxis])
-
- plt.imshow(I)
- plt.colorbar();
<matplotlib.figure.Figure at 0x21e8d1cc9b0>
In [ ]
plt.imshow(I, cmap='gray');
<matplotlib.figure.Figure at 0x21e8d34a208>
In [ ]
- plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
- plt.colorbar()
- plt.clim(-1, 1);
<matplotlib.figure.Figure at 0x21e8e533160>
In [ ]
- ax1 = plt.axes()
- ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])
<matplotlib.figure.Figure at 0x21e8d416518>
In [ ]
- fig = plt.figure()
- ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-1.2, 1.2))
- ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))
-
- x = np.linspace(0, 10)
- ax1.plot(np.sin(x));
- ax2.plot(np.cos(x));
<matplotlib.figure.Figure at 0x21e8d3cd198>
In [ ]
- for i in range(1, 7):
- plt.subplot(2, 3, i)
- plt.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')
-
- # 方法二
- # fig = plt.figure()
- # fig.subplots_adjust(hspace=0.4, wspace=0.4)
- # for i in range(1, 7):
- # ax = fig.add_subplot(2, 3, i)
- # ax.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')
<matplotlib.figure.Figure at 0x21e8e4cd240>
In [ ]
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
<matplotlib.figure.Figure at 0x21e8e4692b0>
In [ ]
- for i in range(2):
- for j in range(3):
- ax[i, j].text(0.5, 0.5, str((i, j)), fontsize=18, ha='center')
- fig
<matplotlib.figure.Figure at 0x21e8e4692b0>
Image Name
In [ ]
- grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
- plt.subplot(grid[0, 0])
- plt.subplot(grid[0, 1:])
- plt.subplot(grid[1, :2])
- plt.subplot(grid[1, 2]);
<matplotlib.figure.Figure at 0x21e8ee619b0>
In [ ]
- mean = [0, 0]
- cov = [[1, 1], [1, 2]]
- x, y = np.random.multivariate_normal(mean, cov, 3000).T
-
- # Set up the axes with gridspec
- fig = plt.figure(figsize=(6, 6))
- grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
- main_ax = fig.add_subplot(grid[:-1, 1:])
- y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
- x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)
-
- # scatter points on the main axes
- main_ax.scatter(x, y,s=3,alpha=0.2)
-
- # histogram on the attached axes
- x_hist.hist(x, 40, histtype='stepfilled',
- orientation='vertical')
- x_hist.invert_yaxis()
-
- y_hist.hist(y, 40, histtype='stepfilled',
- orientation='horizontal')
- y_hist.invert_xaxis()
<matplotlib.figure.Figure at 0x21e8ee34cf8>
In [ ]
- from mpl_toolkits import mplot3d
- fig = plt.figure()
- ax = plt.axes(projection='3d')
<matplotlib.figure.Figure at 0x21e90543da0>
In [ ]
- ax = plt.axes(projection='3d')
-
- # Data for a three-dimensional line
- zline = np.linspace(0, 15, 1000)
- xline = np.sin(zline)
- yline = np.cos(zline)
- ax.plot3D(xline, yline, zline);
<matplotlib.figure.Figure at 0x21e8f117d30>
In [ ]
- ax = plt.axes(projection='3d')
- zdata = 15 * np.random.random(100)
- xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
- ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
- ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');
<matplotlib.figure.Figure at 0x21e8f1734a8>
In [ ]
- import pandas as pd
- df = pd.read_csv('Pokemon.csv')
In [ ]
- pokemon = df['Name'][:5]
- hp = df['HP'][:5]
- attack = df['Attack'][:5]
- defense = df['Defense'][:5]
- ind = [x for x, _ in enumerate(pokemon)]
-
- plt.figure(figsize=(10,10))
- plt.bar(ind, defense, width=0.8, label='Defense', color='blue', bottom=attack+hp)
- plt.bar(ind, attack, width=0.8, label='Attack', color='gold', bottom=hp)
- plt.bar(ind, hp, width=0.8, label='Hp', color='red')
-
- plt.xticks(ind, pokemon)
- plt.ylabel("Value")
- plt.xlabel("Pokemon")
- plt.legend(loc="upper right")
- plt.title("5 Pokemon Defense & Attack & Hp")
- plt.show()
<matplotlib.figure.Figure at 0x21e8f9e5c18>
In [ ]
- N = 5
- pokemon_hp = df['HP'][:5]
- pokemon_attack = df['Attack'][:5]
-
- ind = np.arange(N)
- width = 0.35
- plt.bar(ind, pokemon_hp, width, label='HP')
- plt.bar(ind + width, pokemon_attack, width,label='Attack')
-
- plt.ylabel('Values')
- plt.title('Pokemon Hp & Attack')
-
- plt.xticks(ind + width / 2, (df['Name'][:5]),rotation=45)
- plt.legend(loc='best')
- plt.show()
<matplotlib.figure.Figure at 0x21e8f9e5278>
In [ ]
- x = df['Name'][:4]
- y1 = df['HP'][:4]
- y2 = df['Attack'][:4]
- y3 = df['Defense'][:4]
-
- labels = ["HP ", "Attack", "Defense"]
-
- fig, ax = plt.subplots()
- ax.stackplot(x, y1, y2, y3)
- ax.legend(loc='upper left', labels=labels)
- plt.xticks(rotation=90)
- plt.show()
<matplotlib.figure.Figure at 0x21e8fcfb4e0>
In [ ]
- x = df['Name'][:5]
- y1 = df['HP'][:5]
- y2 = df['Attack'][:5]
- y3 = df['Defense'][:5]
-
- # Create two subplots sharing y axis
- fig, (ax1, ax2,ax3) = plt.subplots(3, sharey=True)
-
- ax1.plot(x, y1, 'ko-')
- ax1.set(title='3 subplots', ylabel='HP')
-
- ax2.plot(x, y2, 'r.-')
- ax2.set(xlabel='Pokemon', ylabel='Attack')
-
- ax3.plot(x, y3, ':')
- ax3.set(xlabel='Pokemon', ylabel='Defense')
-
- plt.show()
<matplotlib.figure.Figure at 0x21e8ee34630>
In [ ]
- plt.plot(df['HP'][:15], '-r',label='HP')
- plt.plot(df['Attack'][:15], ':g',label='Attack')
- plt.legend();
<matplotlib.figure.Figure at 0x21e8f9d68d0>
In [ ]
- x = df['Attack']
- y = df['Defense']
- colors = df['HP']
-
- plt.scatter(x, y, c=colors, alpha=0.5)
- plt.title('Scatter plot')
- plt.xlabel('HP')
- plt.ylabel('Attack')
- plt.colorbar();
<matplotlib.figure.Figure at 0x21e8fa0f358>
In [ ]
- x = df['Attack']
- num_bins = 10
- n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
- plt.title('Histogram')
- plt.xlabel('Attack')
- plt.ylabel('Value')
- plt.show()
<matplotlib.figure.Figure at 0x21e8eee0e80>
In [ ]
- plt.figure(1, figsize=(8,8))
- df['Type 1'].value_counts().plot.pie(autopct="%1.1f%%")
- plt.legend()
<matplotlib.legend.Legend at 0x21e8f131c88>
<matplotlib.figure.Figure at 0x21e8f9c7d68>
In [ ]
- ax = df['Type 1'].value_counts().plot.bar(figsize = (12,6),fontsize = 14)
- ax.set_title("Pokemon Type 1 Count", fontsize = 20)
- ax.set_xlabel("Pokemon Type 1", fontsize = 20)
- ax.set_ylabel("Value", fontsize = 20)
-
- plt.show()
<matplotlib.figure.Figure at 0x21e8fcf6a58>
In [ ]
- import seaborn as sns
-
- top_10_pokemon=df.sort_values(by='Total',ascending=False).head(10)
- corr=top_10_pokemon.corr()
-
- fig, ax=plt.subplots(figsize=(10, 6))
- sns.heatmap(corr,annot=True)
- ax.set_ylim(9, 0)
- plt.show()
<matplotlib.figure.Figure at 0x21e8fc14710>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。