简体   繁体   中英

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. The x-axis is simply a time series and the y-axis are values are random integers between -5000 and 5000 roughly.

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?

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. 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.

Here you only want two values, so c= np.sign(df.y) would be an appropriate choice.

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. The condition would be if >0 or not. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM