【问题标题】:Matplotlib: how to classify values/data in a scatter plot?Matplotlib:如何在散点图中对值/数据进行分类?
【发布时间】:2021-07-10 23:58:51
【问题描述】:

我正在尝试创建一个散点图,在图表上,您可以区分两件事:

  1. 按颜色。例如,如果值为负,则颜色为红色,如果值为正,则颜色为蓝色。

  2. 按标记大小。例如,如果它在 -0.20 和 0 之间的值大小为 100,如果值在 0 和 0.1 之间,大小为 200,如果值在 0.5 和 1 之间,大小为 300 等等...

这是我正在处理的一些数据(以防万一):

0    0.15
1    0.04
2    0.02
3    0.01
4   -0.03
5   -0.07
6   -0.25
7   -0.27
8   -0.30

我尝试了以下方法:

fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(1, 1, 1) 
    
res = np.genfromtxt(os.path.join(folder, 'residuals.csv'), delimiter=',', names=True)

for name in res.dtype.names[1:]: 
    plt.scatter(res.x, res.y, s=200, c=res.residual, cmap='jet')

这很好用,但它只按颜色对我的数据进行排序。大小是一样的,我不知道哪个是负值/正值,所以这就是为什么我要寻找前面提到的这两个条件。

非常感谢任何帮助!

【问题讨论】:

    标签: python pandas dataframe matplotlib scatter-plot


    【解决方案1】:

    Seaborn 的scatterplot 允许根据变量着色和大小。这是使用您的数据类型时的样子。

    import matplotlib.pyplot as plt
    from matplotlib.colors import TwoSlopeNorm
    import numpy as np
    import seaborn as sns
    
    res = np.array([0.15, 0.04, 0.02, 0.01, -0.03, -0.07, -0.25, -0.27, -0.30])
    x = np.arange(len(res))
    y = np.ones(len(res))
    hue_norm = TwoSlopeNorm(vcenter=0)  # to make sure the center color goes to zero
    ax = sns.scatterplot(x=x, y=y, hue=res, hue_norm=hue_norm, size=res, sizes=(100, 300), palette='Spectral')
    
    for xi, resi in zip(x, res):
        ax.text(xi, 1.1, f'{resi:.2f}', ha='center', va='bottom')
    ax.set_ylim(0.75, 2)
    ax.set_yticks([])
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2013-06-16
      • 2014-06-16
      • 2016-11-20
      • 1970-01-01
      相关资源
      最近更新 更多