[英]Pandas Plot With Positive Values One Color And Negative Values Another
I have a pandas dataframe where I am plotting two columns out the 12, one as the x-axis and one as the y-axis. 我有一个pandas数据框,我在其中绘制了12列中的两列,一列为x轴,另一列为y轴。 The x-axis is simply a time series and the y-axis are values are random integers between -5000 and 5000 roughly.
x轴只是一个时间序列,y轴是粗略的-5000到5000之间的随机整数。
Is there any way to make a scatter plot using only these 2 columns where the positive values of y are a certain color and the negative colors are another color? 有没有办法只使用这两列来制作散点图,其中y的正值是某种颜色而负颜色是另一种颜色?
I have tried so many variations but can't get anything to go. 我尝试了很多变化,但无法得到任何东西。 I tried diverging color maps, colormeshs, using seaborn colormaps and booleans masks for neg/positive numbers.
我尝试使用seaborn colormaps和booleans mask为delta / positive数字分散颜色映射,colormeshs。 I am at my wits end.
我没办法。
The idea to use a colormap to colorize the points of a scatter is of course justified. 使用色彩图对分散点进行着色的想法当然是合理的。 If you're using the
plt.scatter
plot, you can supply the values according to which the colormap chooses the color in the c
argument. 如果您正在使用
plt.scatter
图,则可以提供colormap根据c
参数中的颜色选择的值。
Here you only want two values, so c= np.sign(df.y)
would be an appropriate choice. 在这里你只需要两个值,所以
c= np.sign(df.y)
将是一个合适的选择。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'x': np.arange(25), 'y': np.random.normal(0,2500,25)})
fig, ax = plt.subplots()
ax.scatter(df.x, df.y, c=np.sign(df.y), cmap="bwr")
plt.show()
Make 2 separate dataframes by using boolean masking and the where keyword. 使用布尔掩码和where关键字创建2个单独的数据帧。 The condition would be if >0 or not.
条件是if> 0或不是。 Then plot both datframes one by one ,one top of the other, with different parameters for the color.
然后逐个绘制两个数据帧,一个在另一个顶部,使用不同的颜色参数。
Split dataframe and plot them separately: 拆分数据框并分别绘制它们:
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'x': np.arange(20), 'y': np.random.randn(20)})
# split dataframes
df_plus = df[df.y >= 0]
df_minus = df[df.y < 0]
print df_plus
print df_minus
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# plot scatter
ax.scatter(df_plus.x, df_plus.y, color='r')
ax.scatter(df_minus.x, df_minus.y, color='b')
ax.autoscale()
plt.show()
If you want plot negative datframe as positive write df.minus.y = -df_minus.y
. 如果您希望绘制负数据帧为正写入
df.minus.y = -df_minus.y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.