matplotlib 如何改变酒吧的宽度,同时保持一个均匀的空间周围的所有酒吧

wpcxdonn  于 2023-08-06  发布在  其他
关注(0)|答案(2)|浏览(71)

我正尝试使用pandas制作一个条形图,其中所有条形周围的空间相等。当我没有指定width时,这可以很好地开箱即用。问题是,当我指定width时,图表左侧和右侧的边距没有改变,这使得最左侧和最右侧的栏周围的空间比其他栏大。我试过用ax.margins(x=0)调整边距,但没有效果。我怎样才能保持一个均匀的空间为所有酒吧?

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

matplotlib.use('TkAgg')

print(matplotlib.__version__)  # 3.5.3
print(pd.__version__)  # 1.3.5

def grid_in_between(ax):
    """Create gridlines in between (major) data axis values using minor gridlines

    Args:
        ax: Matplotlib axes
    """
    ticks = ax.get_xticks()
    ax.set_xticks(np.array(ticks[:-1]) + np.diff(ticks) / 2, minor=True)
    ax.grid(visible=True, axis='x', which='minor')
    ax.grid(visible=False, axis='x', which='major')
    ax.tick_params(which='minor', length=0, axis='x')

df = pd.DataFrame({'value': range(8)})

fig, ax = plt.subplots(1, 2)
df.plot.bar(ax=ax[0])
df.plot.bar(ax=ax[1], width=.95)
grid_in_between(ax[0])
grid_in_between(ax[1])
ax[0].set_title('Evenly spaced')
ax[1].set_title('Parameter width\nmakes first and last space bigger')
ax[1].margins(x=0)  # no effect
plt.show()

字符串


的数据

tjjdgumg

tjjdgumg1#

设置x轴限制以校正宽度:


的数据

barwidth = 0.95
df.plot.bar(ax=ax[1], width=barwidth)
.
.
.
#Set the x axis limits
ax[1].set_xlim(
    df.index.min() - barwidth/2 - (1 - barwidth) / 2,
    df.index.max() + barwidth/2 + (1 - barwidth) / 2
)

字符串

gk7wooem

gk7wooem2#

您确实应该设置X轴限制,但不要太花哨,只需取最小/最大刻度-/+ 0.5即可。
让我们将此作为最后一行添加到grid_in_between函数:

def grid_in_between(ax):
    """Create gridlines in between (major) data axis values using minor gridlines
    Args:
        ax: Matplotlib axes
    """
    ticks = ax.get_xticks()
    ax.set_xticks(np.array(ticks[:-1]) + np.diff(ticks) / 2, minor=True)
    ax.grid(visible=True, axis='x', which='minor')
    ax.grid(visible=False, axis='x', which='major')
    ax.tick_params(which='minor', length=0, axis='x')
    ax.set_xlim(min(ticks)-0.5, max(ticks)+0.5)

字符串
输出量:
x1c 0d1x的数据

相关问题