2024-10-01 07:33:51 发布
网友
我用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')
但我真正想要的是根据值是正还是负有不同的颜色。在
首先,您需要计算柱状图条形图的高度和位置。然后,您需要创建一个掩码来过滤正反数据。最后,分别绘制条形图的每个子集,并在每次调用函数plt.bar()时设置颜色。在
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()
# 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是一种制作颜色的方法。你必须提供一定数量的红,绿,蓝+透明度,它返回一个颜色。在
你可以在事后给这些条子上色。在
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()
相反,如果你想绘制一个直方图值的条形图(就像另一个答案所建议的那样),它应该看起来像
首先,您需要计算柱状图条形图的高度和位置。然后,您需要创建一个掩码来过滤正反数据。最后,分别绘制条形图的每个子集,并在每次调用函数
plt.bar()
时设置颜色。在你的数据看起来像是假的:
现在让我们学习3个颜色利用的例子:
使用RGB的统一颜色 RGB是一种制作颜色的方法。你必须提供一定数量的红,绿,蓝+透明度,它返回一个颜色。在
^{pr2}$你可以在事后给这些条子上色。在
相反,如果你想绘制一个直方图值的条形图(就像另一个答案所建议的那样),它应该看起来像
^{pr2}$相关问题 更多 >
编程相关推荐