python - Matplotlib:将一组散点图数据带到前面

标签 python matplotlib scatter

我有一系列带有红色和蓝色标记的子图,我对红色标记最感兴趣,所以想把它们放在图的前面:

enter image description here

数据结构是这样的:

            SzT     Pcp     Pcp_3day    Pcp_7day    Pcp_10day   Pcp_14day   Pcp_21day   Pcp_28day
date        
2017-12-04  0.0     8.382   19.304      21.082      40.132      40.132      42.418      71.374
2017-12-05  0.0     12.192  20.574      33.020      42.164      52.324      52.578      81.534
2017-12-06  0.0     1.016   21.590      33.020      34.290      53.340      53.594      82.550
2017-12-07  0.0     12.700  25.908      45.466      46.990      66.040      66.040      95.250
2017-12-08  0.0     5.080   18.796      50.292      51.816      71.120      71.120      88.900

颜色由每个数据点所属的“SzT”值决定,它是 1 或 0(虽然在上面只显示了“0”)。我用下面的代码构建了它:

colors = {0 : 'b',
          1 : 'r'}


fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111)
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

c = [colors[i] for i in RGDFT8mm['SzT']]
m = [marker[i] for i in RGDFT8mm['SzT']]
ax1.scatter(RGDFT8mm['Pcp'], RGDFT8mm['Pcp_3day'], c=c)
ax2.scatter(RGDFT8mm['Pcp'], RGDFT8mm['Pcp_7day'], c=c)
ax3.scatter(RGDFT8mm['Pcp'], RGDFT8mm['Pcp_14day'], c=c)
ax4.scatter(RGDFT8mm['Pcp'], RGDFT8mm['Pcp_28day'], c=c)

ax.set_title('Daily Rainfall vs antecedent rainfall from Rain Gauges 2001-2017')
ax.set_xlabel('Daily Rainfall (mm)')
ax.set_ylabel('Antecedent rainfall (mm)')
ax.set_yticklabels([])
ax.set_xticklabels([])

ax1.set_title('3 Day')
ax2.set_title('7 Day')
ax3.set_title('14 Day')
ax4.set_title('28 Day')

我在别处找不到任何有用的信息。有什么想法吗?

谢谢!

更新:对于糟糕的原始结构表示歉意,我已经在 FYI 上方添加了数据结构。

最佳答案

起初,在不知道数据框中的数据结构的情况下很难说出具体的事情,所以请考虑发布,例如RGDFT8mm.head()

就是说,我至少从您的代码中看到您在一个数据框中混合了红色和蓝色数据,而没有在散点图之前对其进行分组(=分离)。因此,一个分散命令包含两种颜色,因此不可能在前景中获得一种颜色。
如果您重组以便每个散点命令仅绘制一种颜色,则每个散点图都将绘制在前一个散点图之上,除此之外,您可以使用 zorder kwarg 来定义每个数据集的层以你自己的意愿。

对于分组,您可以使用 RGDFT8mm.groupby('SzT') 之类的东西 - 但是,为了从这里提供有用的提示,我宁愿等待确切地了解您的数据帧结构。
但我的第一个猜测是:

for grpname, grpdata in RGDFT8mm.groupby('SzT'):
    ax1.scatter(grpdata['Pcp'], grpdata['Pcp_3day'])
    ax2.scatter(grpdata['Pcp'], grpdata['Pcp_7day'])
    ax3.scatter(grpdata['Pcp'], grpdata['Pcp_14day'])
    ax4.scatter(grpdata['Pcp'], grpdata['Pcp_28day'])

编辑 说明示例

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

data = lambda n: np.random.lognormal(sigma=.5, size=n)
np.random.seed(42)
df = pd.DataFrame({'Pcp': data(500), 'Pcp_3day': data(500), 'SzT': (np.random.random(500)>.9).astype(int)})
print(df.head())

fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)

szt_hi = df.SzT > 0

axs[0, 0].set_title('plot red before blue')
axs[0, 0].scatter(df.loc[szt_hi, 'Pcp'], df.loc[szt_hi, 'Pcp_3day'], c='r', label='SzT=1')
axs[0, 0].scatter(df.loc[~szt_hi, 'Pcp'], df.loc[~szt_hi, 'Pcp_3day'], c='b', label='SzT=0')
axs[0, 0].legend()

axs[0, 1].set_title('plot blue before red')
axs[0, 1].scatter(df.loc[~szt_hi, 'Pcp'], df.loc[~szt_hi, 'Pcp_3day'], c='b', label='SzT=0')
axs[0, 1].scatter(df.loc[szt_hi, 'Pcp'], df.loc[szt_hi, 'Pcp_3day'], c='r', label='SzT=1')
axs[0, 1].legend()

colors = {0 : 'b', 1 : 'r'}
layer = {0: 1, 1: 0}
axs[1, 0].set_title('plot by looping over groups\n(leading to blue first here)')
for i, (n, g) in enumerate(df.groupby('SzT')):
    axs[1, 0].scatter(g.Pcp, g.Pcp_3day, c=colors[i], label='SzT={}'.format(n))
axs[1, 0].legend()

axs[1, 1].set_title('plot by looping over groups \n(leading to blue first here)\nwith manipulating zorder')
for i, (n, g) in enumerate(df.groupby('SzT')):
    axs[1, 1].scatter(g.Pcp, g.Pcp_3day, c=colors[i], zorder=layer[i], label='SzT={}'.format(n))
axs[1, 1].legend()

plt.show()    

enter image description here


...打印 legend 的次数更少,可以像这样遍历所有轴

for a in axs.flatten():
    a.legend()

在绘制所有子图之后。

但是,在您的情况下,与我的示例相比,您的图例都是相同的,因此整个图形的一个图例会更好。为此,只需使用

fig.legend()

可使用与轴图例相同的参数进行修改。

关于python - Matplotlib:将一组散点图数据带到前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53213978/

相关文章:

python - 使用 lmfit 的 2 组织 3 室模型拟合数据

python - 关于管道 stdio 和 subprocess.Popen

python - 如何绘制优化的进度?

python - 动画散点图

python - Matplotlib 按 Y 值绘制散点图颜色

python - 为什么 Python 列表实现为动态数组而不是环形缓冲区?

python - 无法将 django 日期时间字段更新为 Null

python - 是否可以在 matplotlib hexbin 图上绘制相同点的列表?

matlab - 在 Matlab、matplotlib 或 gnuplot 中绘制 3D 密度矩阵

tableau-api - 在 Power BI 中制作散点图