我正在尝试使用Matplotlib创建具有正值和负值的条形图,并且在使负值显示在Y轴上遇到困难。运行代码时,它将正确显示所有正值(用红色标记),但负值根本不显示。 相反,我得到了标记为“ y1”的字符串的正值的重复项。请参阅下面的图片1和我的代码。
我使用的代码是:
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()
数据集有2列Timing Event,其编号为(0,1,2,3 ....),并用作索引和“ Diff Latency”,具有负值和正值。示例数据集如下:
Timing Event Diff Latency
0 -4
1 3
2 1
3 -1
4 2
答案 0 :(得分:1)
如果您只想在不同颜色的条形图中绘制正值和负值,则可以根据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')