Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 478
guy Avatar asked Apr 24 '17 04:04

guy


2 Answers

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()

scatter plot colored according to postive and negative vlaues

like image 87
ImportanceOfBeingErnest Avatar answered Sep 29 '22 01:09

ImportanceOfBeingErnest


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()

enter image description here

If you want plot negative datframe as positive write df.minus.y = -df_minus.y.

like image 36
pcu Avatar answered Sep 29 '22 03:09

pcu