在matplotlib中设置分组条形图之间的间距

zpgglvta  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(126)

我目前正在分析在实地实验中收集的蚯蚓数量数据。我的变量是场地类型(实验场地与参考场地),收集数据的年份,种植的作物和蚯蚓数量。我使用groupby()将蚯蚓按类型,年份和作物分组,并将其显示在条形图中。
但是图中的两组条形图靠得太近了,所以我想增加它们之间的间距。如何在不改变宽度的情况下做到这一点?
我试着为它设置一些代码(在最后),但我总是得到错误:
“TypeError:bar()缺少1个必需的位置参数:'height'”
然而,当我定义高度时,我只是在其他组的条上得到大的蓝色条。
下面是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


data = {'Style': ["Experiment","Reference", "Experiment", "Reference", "Experiment","Reference",
              "Experiment", "Reference"],
        'Year': ["2021", "2021","2022","2022", "2021","2021", "2022", "2022"],
        'Crop': ["Rapeseed", "Rapeseed", "Rapeseed", "Rapeseed",
             "Maize", "Maize", "Maize", "Maize"],
        'Earthworms': [55, 2, 2,6,0,1,7,22]
       }

df = pd.DataFrame(data)

#Set graph properties
fig, ax = plt.subplots(figsize=(15,7))
colors = {"Maize": "#de8f05", "Rapeseed":"#d7bb19"}         
labels = list(colors.keys())

#Create yerr variable
yerr = [10.6926766215636, 1.4142135623731, 0.577350269189626,1.414213562, 0,
       0.707106781186548, 2.857738033, 4.43471156521669]

yerr = np.array(yerr).reshape(2,4)

#Groupby Year, Patchstyle, Crop (ind. variables), EW_num (dep. variable)
df = df.groupby(["Year", "Style", "Crop"])["Earthworms"].sum().unstack().plot.bar(ax=ax, color=colors,     yerr=yerr, width=0.9)

#Assign labels, axis ticks + limit, hide spines  

plt.ylabel("N", size=13, labelpad=10)
plt.yticks(fontsize=12)
plt.xticks(fontsize=12)
ax.set(xlabel=None)

plt.ylim(0,60)    
ax.spines.right.set_visible(False)
ax.spines.top.set_visible(False)

#Create space between two groups of bars
#n_groups = 2
#index = np.arange(n_groups)

#ax.bar(index, height)

字符串

gpnt7bae

gpnt7bae1#

至于在pandas plotting中保持这一点,我发现简单地从plot函数中删除width参数似乎会导致组之间的间距很好:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

data = {
    "Style": [
        "Experiment",
        "Reference",
        "Experiment",
        "Reference",
        "Experiment",
        "Reference",
        "Experiment",
        "Reference",
    ],
    "Year": ["2021", "2021", "2022", "2022", "2021", "2021", "2022", "2022"],
    "Crop": [
        "Rapeseed",
        "Rapeseed",
        "Rapeseed",
        "Rapeseed",
        "Maize",
        "Maize",
        "Maize",
        "Maize",
    ],
    "Earthworms": [55, 2, 2, 6, 0, 1, 7, 22],
}

df = pd.DataFrame(data)

# Set graph properties
fig, ax = plt.subplots(figsize=(15, 7))
colors = {"Maize": "#de8f05", "Rapeseed": "#d7bb19"}
labels = list(colors.keys())

# Create yerr variable
yerr = [
    10.6926766215636,
    1.4142135623731,
    0.577350269189626,
    1.414213562,
    0,
    0.707106781186548,
    2.857738033,
    4.43471156521669,
]

yerr = np.array(yerr).reshape(2, 4)

# Groupby Year, Patchstyle, Crop (ind. variables), EW_num (dep. variable)
df = (
    df.groupby(["Year", "Style", "Crop"])["Earthworms"]
    .sum()
    .unstack()
    .plot.bar(ax=ax, color=colors, yerr=yerr)
)

# Assign labels, axis ticks + limit, hide spines
plt.ylabel("N", size=13, labelpad=10)
plt.yticks(fontsize=12)
plt.xticks(fontsize=12)
ax.set(xlabel=None)

plt.ylim(0, 60)

ax.spines.right.set_visible(False)
ax.spines.top.set_visible(False)

字符串
x1c 0d1x的数据
不过,也许你会对plotly感兴趣(安装起来并不比pandas困难; pip install plotly)。
例如:

import plotly.graph_objects as go

df = df.groupby(["Year", "Style", "Crop"])["Earthworms"].sum().unstack()
x = [[x[n] for x in df.index.values] for n in range(2)]

fig = go.Figure()
fig.add_bar(x=x, y=df.Maize, name="Maize", marker_color="#de8f05")
fig.add_bar(x=x, y=df.Rapeseed, name="Rapeseed", marker_color="#d7bb19")
fig.update_layout(barmode="group")
fig.show()


这会产生更专业的视觉效果:



当然也可以添加误差条(只需添加error_y=dict(type='data', array=yerr) [参见此处的plotly文档])。

smtd7mpg

smtd7mpg2#

我认为有一个更简单的解决方案,只需增加figsize=(x, y)的x维度,然后根据您的喜好调整width
增加figsize会缩放所有内容(条形宽度和间距),这意味着您可以在增加figsize后减小width-参数,从而在与之前相同的条形宽度下增加间距。

相关问题