使用Matplotlib标记数据点的坐标
参考:matplotlib label points with coordinates
在数据可视化领域,Matplotlib是一个非常强大的库,能够帮助我们创建各种各样的图表和图形。有时候,我们需要在图中标记数据点的坐标,以便更清晰地展示数据。本文将介绍如何使用Matplotlib在图表中标记数据点的坐标。
1. 创建一个简单的散点图并标记数据点的坐标
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]))
plt.show()
Output:
2. 在图表中显示坐标轴的值
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]))
plt.xticks(x)
plt.yticks(y)
plt.show()
Output:
3. 标记部分数据点的坐标
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
if x[i] % 2 == 0:
plt.annotate((x[i], y[i]), (x[i], y[i]))
plt.show()
Output:
4. 自定义标记点的样式和颜色
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]), color='red', fontsize=12, weight='bold')
plt.show()
Output:
5. 标记全部数据点的坐标
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]), ha='right', va='bottom')
plt.show()
Output:
6. 在线条图中标记数据点的坐标
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o')
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]))
plt.show()
Output:
7. 标记数据点的坐标并添加箭头指向数据点
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]), arrowprops=dict(facecolor='black'))
plt.show()
Output:
8. 标记数据点的坐标并添加背景色
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]), bbox=dict(facecolor='red', alpha=0.5))
plt.show()
Output:
9. 在饼图中标记数据点的坐标
import matplotlib.pyplot as plt
sizes = [30, 20, 15, 35]
plt.pie(sizes, labels=['A', 'B', 'C', 'D'], autopct='%1.1f%%', startangle=140)
plt.annotate('30%', (0, 0))
plt.annotate('20%', (-1, 0))
plt.annotate('15%', (1, 1))
plt.annotate('35%', (1, -1))
plt.show()
Output:
10. 标记数据点的坐标并添加连线
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
for i in range(len(x)):
plt.plot([x[i], x[i]], [0, y[i]], '--', color='gray')
plt.plot([0, x[i]], [y[i], y[i]], '--', color='gray')
for i, txt in enumerate(y):
plt.annotate((x[i], y[i]), (x[i], y[i]))
plt.scatter(x, y)
plt.show()
Output:
通过以上示例代码,我们可以看到如何使用Matplotlib在数据可视化中标记数据点的坐标。这些技巧可以帮助我们更清晰地展示数据,让图表更具信息量和美观性。