【问题标题】:Plot points in different colors用不同颜色绘制点
【发布时间】:2014-03-07 14:28:58
【问题描述】:

我有一个使用创建的数据框

results = df2[(df2['R'] > 100)].sort(columns='ZR', ascending=False)

我想做

plt.plot(results['ZR'], marker='o')

除了我希望结果['I'] == foo 的点为红色,而结果['I'] != foo 的点为蓝色。

我试过了

firstset = results.ZR[results.I.str.contains('foo')]
secondset = results.ZR[~results.I.str.contains('foo)]
plt.plot(firstset, marker='o', color='red')
plt.plot(secondset, marker='o', color='blue')

但这会从 x 轴 0 开始绘制两半,这不是我需要的。

我会喜欢原来的图表,但有些点是红色的,有些是蓝色的。那不是新的点,也没有改变位置的点。这是原始图表。

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    首先,在没有任何 X 参数的情况下,plt.show 将其假定为从 1 开始的连续整数。为了使用逻辑运算找到正确的索引,请执行以下操作:

    firstIndex = results.index[results.I.str.contains('foo')]
    secondIndex = results.index[~results.I.str.contains('foo)]
    

    如果您的原始索引很复杂,请为新索引创建一个虚拟 pandas DataFrame。

    newDf = pd.DataFrame(range(len(results)))
    firstIndex = newDf.index[results.I.str.contains('foo')]
    secondIndex = newDf.index[~results.I.str.contains('foo')]
    

    这保证会创建两个作为1:230 子集的索引。

    接下来,将字符串限定符传递给plt.plot 以指定颜色和标记类型。

    plt.plot(results['ZR'])
    plt.plot(firstIndex, firstset, "bo")
    plt.plot(secondIndex, secondset, "ro")
    

    这将使用线条绘制整个带下划线的数据,没有点标记。然后它将用各自的颜色覆盖这两个设置点。

    【讨论】:

    • 恐怕这行不通。我真的很想要我在问题中显示的第二张图,但其中一些点是红色的。我不希望图中点的任何位置发生变化,也不希望有任何新点。
    • 抱歉,又多了一个。您需要为firstsetsecondset 指定正确的X 轴点。如果没有,它们会成为从 1 开始的连续点。看到图像中的红色曲线都向 Y 轴移动了吗?那是因为没有通过正确的 X 点。
    • firstIndex 看起来像 [(681, 6024), (681, 6012), (679, 6009), (681, 6004), (669, 6003), (680, 6003), (679 , 6008), (666, 6000), (662, 6019), (669, 6002), (662, 6017)]。你是这个意思吗?您不能在 plt.plot(firstIndex, firstset, "bo") 中使用它。这是因为我索引它的方式。奇怪的是 results.reset_index() 似乎没有帮助。
    • 等等,你没有标准的1:230 索引吗?如果没有,只需从 1:230 创建一个虚拟 pandas DataFrame 并使用它来索引绘图。再次编辑我的回复
    • results = results.reset_index() 修复了它。谢谢!我也期待你的新版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2011-10-10
    • 2018-04-08
    相关资源
    最近更新 更多