首页 > 解决方案 > 关于调色板、图形透明度和 x 轴密度的一些基本 Matplotlib 问题

问题描述

哟,关于stackoverflow的第一个问题。大肆宣传,这是一个菜鸟。:)

我正在使用 Matplotlib 绘制一个基本的条形图:

ind = np.arange(num_of_values)  # the x locations for the groups
graph_values = dataCount.iloc[:,2]
width = 0.30       # the width of the bars

plt.style.use("ggplot")
fig, ax = plt.subplots()
barplot = ax.bar(ind+0.15, graph_values, width, color='blue', edgecolor='black')

ax.set(ylim=[0,1])
ax.set_ylabel('Probability', fontsize=12)
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('1', '2', '3'))

autolabel(barplot)

plt.show()

我在想:

  1. 我可以设置绘制条的填充不透明度/透明度吗?
  2. 我可以在不使用 Seaborn 的情况下为图表的条形分配调色板吗?
  3. 我怎样才能简单地让条形更靠近彼此(使每个刻度之间的间距更小)?

标签: pythonmatplotlibgraph

解决方案


欢迎来到 SO。

回复 1:大多数 matplotlib 函数都有一个alpha控制不透明度的参数,它是 0 和 1 之间的浮点数。

barplot = ax.bar(ind+0.15, graph_values, width, color='blue', edgecolor='black', alpha=0.7)

Re 2:您可以直接指定条形的颜色,方法是给它一个命名颜色列表 ( color = ['blue', 'red', 'salmon', 'crimson', 'azure', ...]) 或长度与您的高度相同的颜色值数组。

random_colors = np.random.rand(len(ind) , 3)
barplot = ax.bar(ind+0.15, graph_values, width, color=random_colors, edgecolor='black')

Re 3:减少 x 值:

ind = np.arange(num_of_values/2., step=0.5)  # the x locations for the groups

未来问题的注意事项:

  1. 尽量不要在一篇文章中提出多个问题。

  2. 尝试使您的代码示例自包含。例如,在您的代码段中,我们不知道变量dataCountnum_of_values所以如果您有问题,我们无法自己重现。

快乐编码!


推荐阅读