Axes类是Matplotlib中最常用的类之一。它被用于绘制图形中的坐标系。本文将详细介绍Axes类的各种属性和用法,并提供示例以帮助读者更好地理解其用法。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_title('这是一个标题')
plt.show()
运行结果如下:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
fig, ax = plt.subplots()
ax.scatter(x, y)
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_title('随机散点图')
plt.show()
运行结果如下:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.random.randint(1, 20, size=5)
fig, ax = plt.subplots()
ax.bar(x, y)
ax.set_xticks(x)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
ax.set_xlabel('分类')
ax.set_ylabel('数量')
ax.set_title('柱状图')
plt.show()
运行结果如下:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(1000)
fig, ax = plt.subplots()
ax.hist(x, bins=30, density=True, alpha=0.5)
ax.set_xlabel('值')
ax.set_ylabel('频率')
ax.set_title('直方图')
plt.show()
运行结果如下:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randint(1, 5, size=5)
fig, ax = plt.subplots()
ax.pie(x)
ax.set_title('饼图')
plt.show()
运行结果如下:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y1 = np.random.randint(1, 20, size=5)
y2 = y1 * 2
fig, ax = plt.subplots()
ax.bar(x, y1, label='y1')
ax.bar(x, y2, label='y2')
ax.set_xticks(x)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
ax.set_xlabel('分类')
ax.set_ylabel('数量')
ax.set_title('多个柱状图')
ax.legend()
plt.show()
如下图所示:
本文链接:http://task.lmcjl.com/news/4684.html