简体   繁体   English

在Matplotlib中的条形图上显示负值的问题

[英]Issues in displaying negative values on bar chart in Matplotlib

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. 我正在尝试使用Matplotlib创建一个同时具有正值和负值的条形图,并且在使负值显示在Y轴上遇到困难。 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". 相反,我得到了标记为“ y1”的字符串的正值的重复项。 Please see Image 1 attached and my code below. 请参阅所附的图片1和下面的我的代码。

图片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. 数据集有2列Timing Event,其编号为(0,1,2,3 ....),并用作索引和“ Diff Latency”,具有负值和正值。 Sample dataset is attached below: 示例数据集如下:

Timing Event    Diff Latency
     0               -4
     1                3
     2                1
     3               -1
     4                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')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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