2

I am trying to create a bar chart with both positive and negative values using Matplotlib and experiencing difficulty in getting the negative values to show on Y axis. When the code is run, it'll correctly display all positive values (marked in red color) but the negative ones are not showing at all. Instead I'm getting a duplication of the positive values for the string marked "y1". Please see Image 1 attached and my code below.

Image 1

The code I've used is:

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.pyplot import figure

data = pd.read_csv("C:\samplefile.csv")
fig = plt.figure()
figure(figsize = (22,3))
ax = plt.subplot(111)
x = data['Timing Event']
y = data['Diff Latency'].diff(periods = 1) > 0
y1 = data['Diff Latency'].diff(periods = 1) < 0
y_pos = np.arange(len(x))
plt.bar(y_pos, y, color=(1.0, 0, 0, 0.7))
plt.bar(y_pos, y1, color=(0, 0.6, 0, 0.7))

plt.tight_layout()
plt.show()

The dataset has 2 columns Timing Event in numbers eg.(0,1,2,3....) and used as index and "Diff Latency" which has both negative and positive values. Sample dataset is attached below:

Timing Event    Diff Latency
     0               -4
     1                3
     2                1
     3               -1
     4                2
makman
  • 139
  • 1
  • 3
  • 14
  • What is your expected result like? – gmds Jun 03 '19 at 09:00
  • Hello gmds, the expected result looks like the attached image (Image 1 link above), however the green columns should be displayed on the negative side of the axis. I can generate the negative values on string y but the colour will be red and the end user is not able to tell the difference visually. – makman Jun 03 '19 at 09:14
  • You are not plotting negative values but boolean values. Is `plt.bar(y_pos, -1 * y1, color=(0, 0.6, 0, 0.7))` what you want? – Stop harming Monica Jun 03 '19 at 10:02

1 Answers1

2

If you just want to plot the positive and negative values in different colored bars, you can directly use pandas plotting based on the approach shown here

import pandas as pd
import matplotlib.pyplot as plt 

fig, ax = plt.subplots()

data = pd.DataFrame({'Timing_Event':[0,1,2,3,4], 'Diff_Latency':[-4, 3, 1, -1, 2]})
data['sign'] = data['Diff_Latency'] > 0

data['Diff_Latency'].plot(kind='bar', color=data.sign.map({True: (1.0, 0, 0, 0.7), False: (0, 0.6, 0, 0.7)}), 
                      ax=ax)
ax.axhline(0, color='k')

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71