我使用Python进行了以下绘图:
import matplotlib.pyplot as plt
plt.hist([x*100 for x in relativeError], bins = 100)
plt.xlabel("Relative Error [%]")
plt.ylabel("#samples")
plt.axvline(x=0, linestyle='--',linewidth=1, color='grey')
但是我真正想要的是根据值是正数还是负数来具有不同的颜色。
答案 0 :(得分:3)
您可以在事实之后为条形着色。
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(-20, 15, 5000)
_, _, bars = plt.hist(x, bins = 100, color="C0")
for bar in bars:
if bar.get_x() > 0:
bar.set_facecolor("C1")
plt.xlabel("Relative Error [%]")
plt.ylabel("#samples")
plt.axvline(x=0, linestyle='--',linewidth=1, color='grey')
plt.show()
如果相反,您想绘制直方图值的条形图(如其他答案所示),则看起来像
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(-20, 15, 5000)
hist, edges = np.histogram(x, bins=100)
colors = np.array(["C0", "C1"])[(edges[:-1] > 0).astype(int)]
plt.bar(edges[:-1], hist, width=np.diff(edges), align="edge", color=colors)
plt.xlabel("Relative Error [%]")
plt.ylabel("#samples")
plt.axvline(x=0, linestyle='--',linewidth=1, color='grey')
plt.show()
答案 1 :(得分:0)
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Make a fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
现在让我们研究3个颜色利用示例:
使用RGB的均匀颜色 RGB是一种制作颜色的方法。您必须提供一定数量的红色,绿色和蓝色+透明度,然后它会返回颜色。
plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
plt.xticks(y_pos, bars)
plt.show()
答案 2 :(得分:0)
首先,您需要计算直方图的条形的高度和位置。然后,您需要创建一个掩码以过滤正负数据。最后,分别绘制各个条形子集,并在每次调用函数plt.bar()
时设置颜色。
带有类似于您的虚假数据的示例:
import matplotlib.pyplot as plt
import numpy as np
# generate fake data
N = 1000
data = np.random.normal(loc=-1, size=N) # with average -1
n_bins = 100
heights, bins, _ = plt.hist(data, bins=n_bins) # get positions and heights of bars
bin_width = np.diff(bins)[0]
bin_pos = bins[:-1] + bin_width / 2
plt.figure()
mask = (bin_pos >= 0)
# plot data in two steps
plt.bar(bin_pos[mask], heights[mask], width=bin_width, color='C1')
plt.bar(bin_pos[~mask], heights[~mask], width=bin_width, color='C0')
plt.xlabel("Relative Error [%]")
plt.ylabel("#samples")
plt.axvline(x=0, linestyle='--',linewidth=1, color='grey')
plt.show()