x = np.linspace(0, 10, 100)
y = x\*\*2
plt.scatter(x, y, c=y, cmap="inferno") # 让c随着y的值变化在cmap中进行映射
plt.colorbar() # 输出颜色条
<matplotlib.colorbar.Colorbar at 0x18848d392e8>
颜色配置参考官方文档
https://matplotlib.org/examples/color/colormaps_reference.html
【3】根据数据控制点的大小
x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000\*size, cmap="viridis")
<matplotlib.collections.PathCollection at 0x18847b48748>
【4】透明度
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()
<matplotlib.colorbar.Colorbar at 0x18848f2be10>
【例】随机漫步
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 or 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)) # 设置画布大小
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([])
([], <a list of 0 Text yticklabel objects>)
13.1.3 柱形图
【1】简单柱形图
x = np.arange(1, 6)
plt.bar(x, 2\*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.tick_params(axis="both", labelsize=13)
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)
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)
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)
【2】累加柱形图
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()
<matplotlib.legend.Legend at 0x2052db25cc0>
【3】并列柱形图
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()
<matplotlib.legend.Legend at 0x2052daf35f8>
【4】横向柱形图barh
x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 \* np.arange(1, 6)
plt.barh(x, y, align="center"