簡體   English   中英

matplotlib: 改變 position 的酒吧

[英]matplotlib: changing position of bars

我正在嘗試在 matplotlib 中創建一個條形圖子圖,在 x 軸上有 2 個條形圖。 我創建了以下圖像:

子圖欄

這是使用以下代碼創建的:

import pandas as pd
import matplotlib.pyplot as plt

ydata1=pd.Series.from_array([451,505])
ydata2=pd.Series.from_array([839,286])

fig, (ax1, ax2) = plt.subplots(1,2,sharex='col',sharey='row')
xlabels = ['x1', 'x2']
ax1.bar(xlabels,ydata1, 0.4, align='center') #0.4 is width of bar
ax2.bar(xlabels,ydata2, 0.4, align='center')
plt.show()

我遇到的問題是我想調整 position 的條形,使它們對稱並且與每個面的邊緣等距,而不是在每個面的左右邊緣(如它們當前那樣)。 有什么方法可以調整matplotlib中的條形position使其對稱嗎?

謝謝

要根據條寬和條數獲得准確的邊距,請注意:

  • 條形的中心位於位置0, 1, ..., N-1
  • 兩個柱之間的距離是1-bar_width
  • 第一個柱從0-bar_width/2開始; 要使條形圖和左邊距之間的間距與條形圖本身之間的間距相等,可以將左邊距設置為0-bar_width/2-(1-bar_width)
  • 同樣,右邊距可以設置為N-1+bar_width/2+(1-bar_width)
import matplotlib.pyplot as plt
import numpy as np

N = 8
ydata1 = np.random.randint(200, 800, N)
ydata2 = np.random.randint(200, 800, N)

fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', sharey='row')
xlabels = [f'x{i}' for i in range(1, N + 1)]
width = 0.4
ax1.bar(xlabels, ydata1, width, align='center')
ax2.bar(xlabels, ydata2, width, align='center')
margin = (1 - width) + width / 2
ax1.set_xlim(-margin, len(xlabels) - 1 + margin)
ax2.set_xlim(-margin, len(xlabels) - 1 + margin)
plt.show()

示例圖 8 條

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM