python 如何在2D散点图中为每个组设置单独的颜色[重复]

rvpgvaaj  于 2023-10-15  发布在  Python
关注(0)|答案(1)|浏览(89)

此问题已在此处有答案

Color a scatter plot by Column Values(6个回答)
Setting different color for each series in scatter plot(8个回答)
Scatter plot with legend for each color in c(5个答案)
Scatter plot change color based on value on list(2个答案)
昨天关门了。
我怎么能让每组A,B,C..?
下面是我代码:

import matplotlib.pyplot as plt
import numpy as np

# Data
group_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

data = [
    [0.735721594, 0.619603837, 0.87785673, 0.482125754, 0.0894892, 0.133485767, 0.995450247],
    [0.666117198, 0.52923401, 0.499589112, 0.096963416, 0.308461174, 0.130418723, 0.195501054],
    [0.696378042, 0.437459297, 0.033071186, 0.645614608, 0.99425186, 0.097360026, 0.354376981],
    [0.552392974, 0.668845104, 0.079569268, 0.455465795, 0.353141333, 0.147198273, 0.249947862],
    [0.591065904, 0.34886412, 0.821742243, 0.008845512, 0.259947361, 0.063514992, 0.040540063],
    [0.016209069, 0.092671819, 0.195080351, 0.886493551, 0.745661888, 0.504613173, 0.593546542],
    [0.536218451, 0.466140392, 0.721903277, 0.426671591, 0.648579902, 0.823047029, 0.922809018]
]

# Transpose the data to have groups on the x-axis
data = np.array(data).T

# Create a 2D scatter plot with unique colors for each data point
color_map = plt.cm.get_cmap('tab10', len(group_labels))  # Choose a color map
for i in range(len(group_labels)):
    colors = color_map(np.linspace(0, 1, len(data[i])))
    for j in range(len(data[i])):
        plt.scatter(group_labels[i], data[i][j], label=f'Group {group_labels[i]}', marker='o', s=50, c=colors[j])

# Customize the plot
plt.xticks(rotation=0)
plt.ylabel('Y Values')
plt.tight_layout()

# Show the plot
plt.show()

这就是结果

我怎么能让每组A,B,C..?

ubbxdtey

ubbxdtey1#

一个简单的解决方案是使用seaborn.scatterplot。我使用pandas来操作数据(熔化),然后绘图。

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

# Data
group_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

data = [
    [0.735721594, 0.619603837, 0.87785673, 0.482125754, 0.0894892, 0.133485767, 0.995450247],
    [0.666117198, 0.52923401, 0.499589112, 0.096963416, 0.308461174, 0.130418723, 0.195501054],
    [0.696378042, 0.437459297, 0.033071186, 0.645614608, 0.99425186, 0.097360026, 0.354376981],
    [0.552392974, 0.668845104, 0.079569268, 0.455465795, 0.353141333, 0.147198273, 0.249947862],
    [0.591065904, 0.34886412, 0.821742243, 0.008845512, 0.259947361, 0.063514992, 0.040540063],
    [0.016209069, 0.092671819, 0.195080351, 0.886493551, 0.745661888, 0.504613173, 0.593546542],
    [0.536218451, 0.466140392, 0.721903277, 0.426671591, 0.648579902, 0.823047029, 0.922809018]
]

# Use pandas dataframe; melt and then plot
df = pd.DataFrame(data, columns = group_labels)
df = df.melt(value_vars=group_labels)
sns.scatterplot(df,x='variable', y='value', hue='variable', legend=False )

剧情:

相关问题