不同颜色和标签的散点图

2024-10-03 17:14:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框。它看起来像这样:enter image description here

我试图为每个点创建不同颜色的散点图。我试过:

df.plot.scatter(x='x',y='y',c=df.colors.tolist(), legend=True)

我得到了散点图。但我无法显示“财务”与颜色“#4ce068”相关的标签。你知道吗

我该怎么做?谢谢

我试过:

df.plot.scatter(x='x',y='y',c=df.colors.tolist(),label=df.key.unique.tolist())

这几乎奏效,但事实上有太多的标签和颜色与标签是很难看到。你知道吗

我想有相关的颜色,最好在图表顶部,即标题旁边的关键显示。有可能吗?你知道吗

My dataframe in dictionary format: 

{'key': {0: 'Financials',
1: 'Consumer Discretionary',
2: 'Industrials',
3: 'Communication Services',
4: 'Communication Services',
5: 'Consumer Discretionary',
6: 'Health Care',
7: 'Information Technology',
8: 'Consumer Discretionary',
9: 'Information Technology'},
'x': {0: 1630000.0,
 1: 495800000.0,
 2: 562790000.0,
 3: 690910000.0,
 4: 690910000.0,
 5: 753090000.0,
 6: 947680000.0,
 7: 1010000000.0,
 8: 1090830000.0,
 9: 1193600000.0},
 'y': {0: 0.02549175,
 1: 0.0383163,
 2: -0.09842154,
 3: 0.03876266,
 4: 0.03596279,
 5: 0.01897367,
 6: 0.06159238,
 7: 0.0291209,
 8: 0.003931255,
 9: -0.007134976},
'colors': {0: '#4ce068',
 1: '#ecef4a',
 2: '#ff3c83',
 3: '#ff4d52',
 4: '#ff4d52',
 5: '#ecef4a',
 6: '#00f1d1',
 7: '#d9d9d9',
 8: '#ecef4a',
 9: '#d9d9d9'}}

Tags: keydfinformationplotconsumer颜色标签communication
2条回答

如果你不介意使用plotly,你可以试试

import pandas as pd
import plotly.express as px

px.scatter(df, 'x', 'y', color="key", color_discrete_sequence=df["colors"].tolist())

enter image description here

但是如果你选择了颜色,px.scatter(df, 'x', 'y', color="key")会更好看

enter image description here

有一种方法:

fig, ax = plt.subplots()
for i in df.colors.unique():
    df_color = df[df.colors==i]
    df_color.plot.scatter(x='x',y='y', ax=ax, c=i, label=df_color.key.iloc[0])

ax.legend(loc='best')

你会得到的 enter image description here

相关问题 更多 >