在散点图中绘制标签

时间:2020-02-02 14:58:01

标签: python

我是一名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()

2 个答案:

答案 0 :(得分:0)

使用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()

答案 1 :(得分:0)

我共同构思了此解决方案,该解决方案以规范的Iis数据集为例进行绘制。

 # Load libraries
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt

# Load Iris Flower Dataset
# Load data
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Train A Decision Tree Model
# Create decision tree classifer object
clf = RandomForestClassifier(random_state=0, n_jobs=-1)

# Train model
model = clf.fit(X, y)

# View Feature Importance
# Calculate feature importances
importances = model.feature_importances_

# Visualize Feature Importance
# Sort feature importances in descending order
indices = np.argsort(importances)[::-1]

# Rearrange feature names so they match the sorted feature importances
names = [iris.feature_names[i] for i in indices]


import numpy as np
import matplotlib.pyplot as plt

N = 10
data = X
labels = y

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here