【问题标题】:How can I adjust the space between bars in a stacked barplot (Matplotlib) without compromising the width of the bars? [duplicate]如何在不影响条形宽度的情况下调整堆叠条形图(Matplotlib)中条形之间的空间? [复制]
【发布时间】:2021-08-05 10:31:44
【问题描述】:

我已经花了很长时间在网上寻找解决方案。我用 Matplotlib 创建了一个堆叠的水平条形图。我想增加条之间的空间,但不知道怎么做。

import pandas as pd
import matplotlib.pyplot as plt


d = {
'id': [823,234,213,343,329,289,569,294,295,832],
'dogs': [1,2,3,4,3,5,2,3,4,5], 
'cats': [3,4,5,2,1,3,4,5,3,2,], 
'birds': [1,4,2,3,4,2,3,1,4,2]}

df = pd.DataFrame(data=d)

df.plot(
    x = 'id',
    kind = 'barh',
    stacked = True,
    title = 'Stacked Bar Graph',
    mark_right = True, 
    color=['#D3E0F9','#7AA3F1','#3D68CF'],
    width=0.6)


plt.rc('axes', titlesize=6) #fontsize of the title
plt.rc('axes', labelsize=10) #fontsize of the x and y labels
plt.rc('xtick', labelsize=10) #fontsize of the x tick labels
plt.rc('ytick', labelsize=10) #fontsize of the y tick labels
plt.rc('legend', fontsize=10) #fontsize of the legend

【问题讨论】:

  • 你试过增加你的身材的宽度/高度吗?
  • 我做到了。但我想坚持当前的宽度。但是改变高度不起作用我总是得到错误“barh()为参数'height'获得了多个值”

标签: python matplotlib format bar-chart stacked


【解决方案1】:

在绘图之前设置您的图形大小:

fig, ax = plt.subplots(figsize=(6, 10))
df.plot(
    x="id",
    kind="barh",
    stacked=True,
    title="Stacked Bar Graph",
    mark_right=True,
    color=["#D3E0F9", "#7AA3F1", "#3D68CF"],
    width=0.6,
    # Then plot onto the ax for the `fig`
    ax=ax,
)

【讨论】:

  • 非常感谢,亚历克斯!这有效:-)
  • 使用pandas.DataFrame.plot时设置图形大小的方法不正确。 df.plot(..., figsize=(w, h)).
猜你喜欢
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 2013-12-25
  • 2019-09-14
相关资源
最近更新 更多