2

I have positive and negative values ​​and I want to plot it as a bar chart. I want to plot the classic "green" positive colors and "red" negative values. I have this code currently:

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6]
y2 = [10000,11682,20842,12879,4576,7845]
y1 = [-1456,-10120,-2118,10003,-2004,1644]

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2.plot(x, y2, color='k')
ax2.set_ylabel('Y2 data', color='k')
ax1.bar(x, y1, color='g')
plt.show()

Current plot

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
Minatorecoin
  • 55
  • 1
  • 5

2 Answers2

2

Here you can find an example on how to do this:

import pandas as pd
import plotly.graph_objects as go
import numpy as np

# Data

df = pd.DataFrame({
     'Net':[15,20,-10,-15], 
     'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})

df['Date'] = pd.to_datetime(df['Date'])

## here I'm adding a column with colors
df["Color"] = np.where(df["Net"]<0, 'red', 'green')

# Plot
fig = go.Figure()
fig.add_trace(
    go.Bar(name='Net',
           x=df['Date'],
           y=df['Net'],
           marker_color=df['Color']))
fig.update_layout(barmode='stack')
fig.show()
marsolmos
  • 748
  • 9
  • 24
2

add this line before ploting bar:

color = ['r' if y<0 else 'g' for y in y1]

finally code:

import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y2 = [10000,11682,20842,12879,4576,7845]
y1 = [-1456,-10120,-2118,10003,-2004,1644]

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2.plot(x, y2, color='k')
ax2.set_ylabel('Y2 data', color='k')
color = ['r' if y<0 else 'g' for y in y1]
ax1.bar(x, y1, color=color)
plt.show()

Output:

enter image description here

If you convert y1 array to numpy.array, you can use np.where like below (output from this code is same as output from first code):

y1 = np.array([-1456,-10120,-2118,10003,-2004,1644])
...
ax1.bar(x, y1, color=np.where(y1 < 0, 'r', 'g'))
Matt Hall
  • 7,614
  • 1
  • 23
  • 36
I'mahdi
  • 23,382
  • 5
  • 22
  • 30