AntV L7 气泡图:如何在气泡内添加国家名称 - 代码示例
以下是一个简单的实现示例:
import matplotlib.pyplot as plt
# 生成一些假数据
countries = ['China', 'India', 'United States', 'Indonesia', 'Brazil', 'Pakistan', 'Nigeria', 'Bangladesh', 'Russia', 'Mexico']
gdp = [14.14, 2.85, 21.44, 1.01, 2.05, 0.31, 0.51, 0.30, 1.63, 1.05]
population = [1.40, 1.36, 0.33, 0.27, 0.21, 0.22, 0.20, 0.16, 0.14, 0.13]
# 绘制气泡图
fig, ax = plt.subplots()
ax.scatter(gdp, population, s=[x*1000 for x in population], alpha=0.5)
# 将国家名字添加到气泡中
for i, country in enumerate(countries):
ax.annotate(country, (gdp[i], population[i]), ha='center', va='center')
# 设置图形的标题和坐标轴标签
ax.set_xlabel('GDP (trillions of US dollars)')
ax.set_ylabel('Population (billions)')
ax.set_title('Top 10 Countries by GDP and Population')
plt.show()
在这个示例中,我们使用了annotate()函数将国家名字添加到每个气泡中。该函数需要指定注释的文本内容、注释的位置以及文本的对齐方式。在这里,我们将注释放在气泡的中心,并将文本水平和垂直居中对齐。我们还使用了s参数来控制气泡的大小,使其与国家的人口数量成比例。
原文地址: https://www.cveoy.top/t/topic/lXOL 著作权归作者所有。请勿转载和采集!