%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid") # 设置样式
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y) # x和y数量必须对应
plt.ylabel("squares") # y坐标轴名称
# plt.show()
import matplotlib.pyplot as plt
print(plt.style.available) # 显示可用样式
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
with plt.style.context("seaborn-white"): # 临时使用,仅在其下的代码块中用此样式
plt.plot(x, y)
plt.show()
plt.style.use("seaborn-whitegrid") # 永久设置,如果后面不改的话,会一直延续这种样式
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10 ,100)
plt.plot(x, np.exp(x))
plt.savefig("my_figure.png") # 注意后缀名要写
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100) # 值取得多看起来会比较圆滑,本质上是折线图
plt.plot(x, np.sin(x))
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.cos(x))
plt.plot(x, np.sin(x))
plt.show()
import matplotlib.pyplot as plt
import numpy as np
offsets = np.linspace(0, np.pi, 5)
colors = ["blue", "g", "r", "yellow", "pink"] # 有些颜色可用简写
for offset, color in zip(offsets, colors):
plt.plot(x, np.sin(x-offset), color=color) # color可缩写为c
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 11)
offsets = list(range(8))
linestyles = ["solid", "dashed", "dashdot", "dotted", "-", "--", "-.", ":"] # 后四个是前四个的简写
for offset, linestyle in zip(offsets, linestyles):
plt.plot(x, x+offset, linestyle=linestyle) # linestyle可简写为ls
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
linewidths = (i*2 for i in range(1,5))
for offset, linewidth in zip(offsets, linewidths):
plt.plot(x, x+offset, linewidth=linewidth) # linewidth可简写为lw
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
markers = ["*", "+", "o", "s"]
for offset, marker in zip(offsets, markers):
plt.plot(x, x+offset, marker=marker)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
markers = ["*", "+", "o", "s"]
for offset, marker in zip(offsets, markers):
plt.plot(x, x+offset, marker=marker, markersize=10) # markersize可简写为ms
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_linestyles = ["g-", "b--", "k-.", "r:"] # k是黑色
for offset, color_linestyle in zip(offsets, color_linestyles):
plt.plot(x, x+offset, color_linestyle)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_marker_linestyles = ["g*-", "b+--", "ko-.", "rs:"]
for offset, color_marker_linestyle in zip(offsets, color_marker_linestyles):
plt.plot(x, x+offset, color_marker_linestyle)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.xlim(-1, 7)
plt.ylim(-1.5, 1.5)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis([-2, 8, -2, 2]) # 设置上下限
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis("tight") # 坐标轴适应数据量
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis("equal") # x轴单位的实际长度和y轴单位的实际长度相同
plt.show()
import matplotlib.pyplot as plt
?plt.axis # ipython中专用,命名空间搜索
import matplotlib.pyplot as plt
import numpy as np
x = np.logspace(0, 5, 100)
plt.plot(x, np.log(x))
plt.xscale("log")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.xticks(np.arange(0, 12, step=1))
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.xticks(np.arange(0, 12, step=1), fontsize=15)
plt.yticks(np.arange(0, 110, step=10))
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.tick_params(axis="both", labelsize=15)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.title("A Sine Curve", fontsize=20)
plt.xlabel("x", fontsize=15)
plt.ylabel("sin(x)", fontsize=15)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-", label="Sin")
plt.plot(x, np.cos(x), "r--", label="Cos")
plt.legend()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-", label="Sin")
plt.plot(x, np.cos(x), "r--", label="Cos")
plt.ylim(-1.5, 2)
plt.legend(loc="upper center", frameon=True, fontsize=15) # loc有9种和best,frameon显示底框
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-")
plt.text(3.5, 0.5, "y=sin(x)", fontsize=15)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-")
plt.annotate('local min', xy=(1.5*np.pi, -1), xytext=(4.5, 0),
arrowprops=dict(facecolor='black', shrink=0.1),
) # xy箭头指向的位置,xytext文字位置,shrink箭头长度
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 20)
plt.scatter(x, np.sin(x), marker="o", s=30, c="r") # s 大小 c 颜色
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = x**2
plt.scatter(x, y, c=y, cmap="inferno") # cmap 颜色映射
plt.colorbar() # 显示映射条
plt.show()
https://matplotlib.org/examples/color/colormaps_reference.html
import matplotlib.pyplot as plt
import numpy as np
x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis") # s数据点大小,c和s要跟数据点数量对应
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis", alpha=0.3)
plt.colorbar()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from random import choice
class RandomWalk():
"""一个生产随机漫步的类"""
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
if x_step == 0 and y_step == 0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
rw = RandomWalk(10000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.figure(figsize=(12, 6)) # 画布大小,宽12,高6
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap="inferno", s=1)
plt.colorbar()
plt.scatter(0, 0, c="green", s=100) #起始和结束点设置
plt.scatter(rw.x_values[-1], rw.y_values[-1], c="red", s=100)
plt.xticks([]) # 隐藏坐标轴
plt.yticks([])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 6)
plt.bar(x, 2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red') # align柱子放在数字的中间,edgecolor柱子边缘颜色
plt.tick_params(axis="both", labelsize=13)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 6)
plt.bar(x, 2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.xticks(x, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.tick_params(axis="both", labelsize=13)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = ('G1', 'G2', 'G3', 'G4', 'G5')
y = 2 * np.arange(1, 6)
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.tick_params(axis="both", labelsize=13)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = ["G"+str(i) for i in range(5)]
y = 1/(1+np.exp(-np.arange(5)))
colors = ['red', 'yellow', 'blue', 'green', 'gray']
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color=colors)
plt.tick_params(axis="both", labelsize=13)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y1 = np.random.randint(20, 30, size=5)
y2 = np.random.randint(20, 30, size=5)
plt.bar(x, y1, width=0.5, label="man")
plt.bar(x, y2, width=0.5, bottom=y1, label="women")
plt.legend()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(15)
y1 = x+1
y2 = y1+np.random.random(15)
plt.bar(x, y1, width=0.3, label="man")
plt.bar(x+0.3, y2, width=0.3, label="women")
plt.legend()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 * np.arange(1, 6)
plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue", edgecolor="red") # 注意柱子宽度用height
plt.tick_params(axis="both", labelsize=13)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.subplot(211) # 前两个数字代表两行一列,后面的1代表第一个
plt.plot(t1, f(t1), "bo-", markerfacecolor="r", markersize=5)
plt.title("A tale of 2 subplots")
plt.ylabel("Damped oscillation")
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), "r--")
plt.xlabel("time (s)")
plt.ylabel("Undamped")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.random.random(10)
y = np.random.random(10)
plt.subplots_adjust(hspace=0.5, wspace=0.3) # 定义横向纵向的间隔
plt.subplot(321)
plt.scatter(x, y, s=80, c="b", marker=">")
plt.subplot(322)
plt.scatter(x, y, s=80, c="g", marker="*")
plt.subplot(323)
plt.scatter(x, y, s=80, c="r", marker="s")
plt.subplot(324)
plt.scatter(x, y, s=80, c="c", marker="p")
plt.subplot(325)
plt.scatter(x, y, s=80, c="m", marker="+")
plt.subplot(326)
plt.scatter(x, y, s=80, c="y", marker="H")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return np.exp(-x) * np.cos(2*np.pi*x)
x = np.arange(0.0, 3.0, 0.01)
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3) # 2行3列的网格
plt.subplot(grid[0, 0])
plt.plot(x, f(x))
plt.subplot(grid[0, 1:])
plt.plot(x, f(x), "r--", lw=2)
plt.subplot(grid[1, :])
plt.plot(x, f(x), "g-.", lw=3)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000) # 均值100,标准差15
plt.hist(x, bins=50, facecolor='g', alpha=0.75) # 分成50个区间
plt.show()
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, 50, density=True, color="r")
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, bins=50, density=True, color="r", histtype='step')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
_, bins, __ = plt.hist(x, 50, density=True) # 获得区间
y = norm.pdf(bins, mu, sigma) # 计算符合分布的概率密度
plt.plot(bins, y, 'r--', lw=3)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, 50, density=True, cumulative=True, color="r")
plt.xlabel('Smarts')
plt.ylabel('Cum_Probability')
plt.title('Histogram of IQ')
plt.text(60, 0.8, r'$\mu=100,\ \sigma=15$')
plt.xlim(50, 165)
plt.ylim(0, 1.1)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
class Die():
"模拟一个骰子的类"
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return np.random.randint(1, self.num_sides+1)
# 重复投一个骰子
die = Die()
results = []
for i in range(60000):
result = die.roll()
results.append(result)
plt.hist(results, bins=6, range=(0.75, 6.75), align="mid", width=0.5) # range 从(0.75, 6.75)划分6个区间
# center?
plt.xlim(0 ,7)
plt.show()
# 重复投两个骰子
die1 = Die()
die2 = Die()
results = []
for i in range(60000):
result = die1.roll()+die2.roll()
results.append(result)
plt.hist(results, bins=11, range=(1.75, 12.75), align="mid", width=0.5)
plt.xlim(1 ,13)
plt.xticks(np.arange(1, 14))
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10 ,50)
dy = 0.5
y = np.sin(x) + dy*np.random.randn(50)
plt.errorbar(x, y , yerr=dy, fmt="+b") # fmt设置颜色形状
plt.show()
import matplotlib.pyplot as plt
import numpy as np
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = ['G1', 'G2', 'G3', 'G4', 'G5']
width = 0.35
p1 = plt.bar(ind, menMeans, width=width, label="Men", yerr=menStd)
p2 = plt.bar(ind, womenMeans, width=width, bottom=menMeans, label="Women", yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.yticks(np.arange(0, 81, 10))
plt.legend()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
y = x ** 2
fig = plt.figure(figsize=(8,4), dpi=80) # 图像 figsize画布大小,dpi像素
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # 轴 left, bottom, width, height (range 0 to 1)
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
y = x ** 2
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax2 = fig.add_axes([0.2, 0.5, 0.4, 0.3])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
ax2.plot(y, x, 'g')
ax2.set_xlabel('y')
ax2.set_ylabel('x')
ax2.set_title('insert title')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 3.0, 0.01)
fig= plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax1 = plt.subplot(2, 2, 1)
ax1.plot(t1, f(t1))
ax1.set_title("Upper left")
ax2 = plt.subplot(2, 2, 2)
ax2.plot(t1, f(t1))
ax2.set_title("Upper right")
ax3 = plt.subplot(2, 1, 2) # 注意这里
ax3.plot(t1, f(t1))
ax3.set_title("Lower")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
ax = plt.axes(projection="3d")
# 绘制螺旋线
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline ,zline)
#绘制点
zdata = 15*np.random.random(100)
xdata = np.sin(zdata)
ydata = np.cos(zdata)
ax.scatter3D(xdata, ydata ,zdata, c=zdata, cmap="spring")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y) # 网格化
Z = f(X, Y)
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
t = np.linspace(0, 2*np.pi, 1000)
X = np.sin(t)
Y = np.cos(t)
Z = np.arange(t.size)[:, np.newaxis]
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500) # 500个数据
y = np.cumsum(np.random.randn(500, 6), axis=0) # 500行6列
with plt.style.context("classic"):
plt.plot(x, y) # 自动对齐,绘制出6条曲线
plt.legend("ABCDEF", ncol=2, loc="upper left") # ncol图例分几列
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.linspace(0, 10, 500)
y = np.cumsum(np.random.randn(500, 6), axis=0)
sns.set() # 改变了绘制格式,变成seaborn风格
plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.legend("ABCDEF", ncol=2, loc="upper left")
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 * np.arange(1, 6)
plt.figure(figsize=(8, 4))
plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue")
plt.tick_params(axis="both", labelsize=13)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
plt.figure(figsize=(8, 4))
x = ['G5', 'G4', 'G3', 'G2', 'G1']
y = 2 * np.arange(5, 0, -1)
sns.barplot(y, x, linewidth=5)
plt.show()
import seaborn as sns
sns.barplot?
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
print(iris.head())
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
sns.set()
sns.pairplot(data=iris, hue="species")
plt.show()
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14)
sns.set(font=myfont.get_name())
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
columns=list("ABCD"),
index=np.arange(1000))
print(df.head())
A B C D
0 0.139109 0.128463 -0.084513 0.025072
1 0.085295 0.061121 1.157259 0.896488
2 2.015443 2.157705 0.607950 2.153834
3 0.004897 1.885500 0.199746 2.315296
4 -0.828913 1.183246 2.914528 1.882888
df.plot()
plt.show()
import pandas as pd
df = pd.DataFrame()
df.plot?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
print(df2)
a b c d
0 0.192956 0.043906 0.485144 0.795992
1 0.584856 0.473277 0.703299 0.189399
2 0.860249 0.857595 0.453057 0.254671
3 0.334403 0.761708 0.343463 0.188714
4 0.713408 0.380034 0.136699 0.045663
5 0.268257 0.701495 0.087406 0.941839
6 0.373573 0.483803 0.537277 0.847954
7 0.324497 0.534841 0.786176 0.057222
8 0.527766 0.129430 0.745205 0.852565
9 0.410403 0.356154 0.050476 0.562084
df2.plot.bar()
plt.show()
df2.plot.bar(stacked=True)
plt.show()
df2.plot.barh(stacked=True)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df4 = pd.DataFrame({"A": np.random.randn(1000) - 3, "B": np.random.randn(1000),
"C": np.random.randn(1000) + 3})
print(df4.head())
A B C
0 -2.974090 0.811919 1.454981
1 -3.918316 1.246171 3.292422
2 -3.584788 1.339561 4.249672
3 -3.927277 0.368552 3.799760
4 -3.020831 1.555329 3.881246
df4.plot.hist(bins=50)
plt.show()
df4['A'].plot.hist(cumulative=True)
plt.show()
df4['A'].plot(kind="kde")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
columns=list("ABCD"),
index=np.arange(1000))
print(df.head())
A B C D
0 0.862603 0.716191 -0.962349 0.571769
1 -0.011500 0.771621 -0.545608 1.226492
2 0.475496 0.412311 -1.535971 2.822753
3 0.809000 0.751493 -1.513082 2.713575
4 1.081569 0.719442 -3.359304 3.251815
df.diff().hist(bins=50, color="r")
plt.show()
import pandas as pd
df = pd.DataFrame()
df.hist?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
housing = pd.read_csv("housing.csv")
housing.head()
longitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value ocean_proximity
0 -122.23 37.88 41.0 880.0 129.0 322.0 126.0 8.3252 452600.0 NEAR BAY
1 -122.22 37.86 21.0 7099.0 1106.0 2401.0 1138.0 8.3014 358500.0 NEAR BAY
2 -122.24 37.85 52.0 1467.0 190.0 496.0 177.0 7.2574 352100.0 NEAR BAY
3 -122.25 37.85 52.0 1274.0 235.0 558.0 219.0 5.6431 341300.0 NEAR BAY
4 -122.25 37.85 52.0 1627.0 280.0 565.0 259.0 3.8462 342200.0 NEAR BAY
"""基于地理数据的人口、房价可视化"""
# 圆的半径大小代表每个区域人口数量(s),颜色代表价格(c),用预定义的jet表进行可视化
# x经度,y纬度
#有圈的地方代表有城市,圈越大,人口越多,颜色偏蓝说明房价低,偏红说明房价高
with sns.axes_style("white"):
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.6,
s=housing["population"]/100, label="population",
c="median_house_value", cmap="jet", colorbar=True, figsize=(12, 8))
plt.legend()
plt.axis([-125, -113.5, 32, 43])
plt.show()
housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.8)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
columns=list("ABCD"),
index=np.arange(1000))
print(df.head())
A B C D
0 -0.841199 0.021080 0.679416 -1.115123
1 -1.352381 0.493308 1.756238 -1.723150
2 -2.068088 -1.531768 0.801734 -1.277159
3 -0.445886 -3.386234 0.727494 -0.862176
4 1.311162 -5.831062 1.646270 0.099221
df.plot(subplots=True, figsize=(6, 16))
plt.show()
df.plot(subplots=True, layout=(2, 2), figsize=(16, 6), sharex=False)
plt.show()
https://www.pypandas.cn/docs/user_guide/visualization.html#plot-formatting