gpt4 book ai didi

python - 在散点图中绘制标签

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:32 25 4
gpt4 key购买 nike

我是一个Python初学者,正在尝试制作太阳系的对数图。快完成了,但我想在图中添加行星名称。关于如何做到这一点有什么建议吗?

这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

mass = {
"Mercury": 0.330*(10**24),
"Venus": 4.87*(10**24),
"Earth": 5.97*(10**24)

}

radius = {
"Mercury": (4879/2)*(10**3),
"Venus": (12104/2)*(10**3),
"Earth": (12756/2)*(10**3)
}

df_mass = pd.DataFrame.from_dict(mass, orient='index', columns=['kgs'])
mass = pd.to_numeric(df_mass['kgs'])

df_radius = pd.DataFrame.from_dict(radius, orient='index', columns=['m'])
radius = pd.to_numeric(df_radius['m'])

colors = np.random.rand(3)
scalar = 500

plt.xlabel('Mass (kgs)')
plt.ylabel('Radius (m)')
plt.title('Logarithmic chart of solar system planets')
plt.scatter(mass, radius, c=colors, s=scalar)
plt.grid()
plt.xscale("log")
plt.yscale("log")
plt.show()

最佳答案

使用annotate方法。

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

mass = {
"Mercury": 0.330*(10**24),
"Venus": 4.87*(10**24),
"Earth": 5.97*(10**24)

}

radius = {
"Mercury": (4879/2)*(10**3),
"Venus": (12104/2)*(10**3),
"Earth": (12756/2)*(10**3)
}

###Create a list with the names of the planets
names = ["Mercury", "Venus", "Earth"]

df_mass = pd.DataFrame.from_dict(mass, orient='index', columns=['kgs'])
mass = pd.to_numeric(df_mass['kgs'])

df_radius = pd.DataFrame.from_dict(radius, orient='index', columns=['m'])
radius = pd.to_numeric(df_radius['m'])

colors = np.random.rand(3)
scalar = 500

plt.xlabel('Mass (kgs)')
plt.ylabel('Radius (m)')
plt.title('Logarithmic chart of solar system planets')
plt.scatter(mass, radius, c=colors, s=scalar)

### Add the names of the planets to the graph
for index, name in enumerate(names):
plt.annotate(name, (mass[name], radius[name]))

plt.grid()
plt.xscale("log")
plt.yscale("log")
plt.show()

关于python - 在散点图中绘制标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60027327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com