简体   繁体   English

如何在刻度(matplotlib)之间对齐条形图中的条?

[英]How to align the bars in a bar chart between ticks (matplotlib)?

I need to align the bars in my plots to be centered between the x axis tick lines in matplotlib.我需要将图中的条形对齐到 matplotlib 中 x 轴刻度线之间的中心。 I have tried using the option align='edge' which will move the bar towards the edge of the tick, but wont align it between ticks, I'm also not willing to widen the bars so that there is no white space between bars.我曾尝试使用选项align='edge'将条形移向刻度线的边缘,但不会在刻度之间对齐,我也不愿意加宽条形,以便条形之间没有空白。

I have data with the form:我有以下形式的数据:

import matplotlib.pyplot as plt    
import numpy as np    
data = np.asarray([['7 Jan.',  60000],
                   ['14 Jan.', 37000],
                   ['21 Jan.', 32000]])

And I want to make a bar plot with it:我想用它制作一个条形图:

x = data[:, 0]
y = data[:, 1].astype(np.int)
plt.bar(x, y, width=0.7, color='#A90000')
plt.show()

Which yields:其中产生:

在此处输入图片说明

Also, there's this tutorial which seems to approach the problem, but I haven't been able to my code.此外,还有this tutorial似乎解决了这个问题,但我无法使用我的代码。 Any help is appreciated.任何帮助表示赞赏。

You're plotting categorical data.您正在绘制分类数据。 That is some strings like ["Apple", "Banana", "Cherry"] .那是一些像["Apple", "Banana", "Cherry"]这样的字符串。 Now if you want to have bars in between categories, it's not really clear what unit that would be.现在,如果您想在类别之间设置条形,则不太清楚那将是什么单位。 What's half way between "Apple" and "Banana" ? "Apple""Banana"中间位置是什么? Maybe "Aubergine" ?也许是"Aubergine" But one cannot know.但谁也不能知道。

So it's probably best to give up the categorical plot.所以最好放弃分类图。 Now you can of course map categories to numbers.现在您当然可以将类别映射到数字。 So first category corresponds to 0 , second to 1 etc. Then it's easy to place the bars half way in between, at 0.5, 1.5, ... .所以第一类对应于0 ,第二类对应于1等等。然后很容易将条形放在中间的中间,在0.5, 1.5, ...

import matplotlib.pyplot as plt    
import numpy as np    
data = np.asarray([['7 Jan.',  60000],
                   ['14 Jan.', 37000],
                   ['21 Jan.', 32000]])

cats = data[:, 0]
x = np.arange(len(cats)) + 0.5
y = data[:, 1].astype(np.int)

plt.bar(x, y, width=0.7, color='#A90000')
plt.xticks(x-0.5, cats)
plt.show()

在此处输入图片说明

Somehow the plot looks like it's missing the last label though, which is simply not present in your list.不知何故,情节看起来好像缺少最后一个标签,但它根本没有出现在您的列表中。 You could of course add it manually, if you want.如果需要,您当然可以手动添加它。

An alternative is to work with actual dates.另一种方法是使用实​​际日期。 Since your categories actually correspond to dates that should be possible.由于您的类别实际上对应于应该可能的日期。

from datetime import datetime
import matplotlib.pyplot as plt    
import numpy as np    
data = np.asarray([['7 Jan.',  60000],
                   ['14 Jan.', 37000],
                   ['21 Jan.', 32000]])

# convert categories to dates
xt = [datetime.strptime(d, "%d %b.") for d in data[:, 0]]
# assume all dates are equally spaced
dt = (xt[1] - xt[0])/2
# get bar positions by adding half the interval to each date
x = [tp + dt for tp in xt]

y = data[:, 1].astype(np.int)

plt.bar(x, y, width=(0.7*2*dt).days, color='#A90000')
plt.xticks(xt, data[:, 0])
plt.show()

The resulting plot is visually exactly the same as above, however, the xaxis is now in units of datetime.结果图在视觉上与上面完全相同,但是,xaxis 现在以日期时间为单位。 This allows to use tickers and formatters instead of manually placing the ticks and labels.这允许使用代码和格式器而不是手动放置刻度和标签。

import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt  
import matplotlib.dates as mdates


data = np.asarray([['7 Jan.',  60000],
                   ['14 Jan.', 37000],
                   ['21 Jan.', 32000]])

# convert categories to dates
xt = [datetime.strptime(d, "%d %b.") for d in data[:, 0]]
# assume all dates are equally spaced
dt = (xt[1] - xt[0])/2
# get bar positions by adding half the interval to each date
x = [tp + dt for tp in xt]

y = data[:, 1].astype(np.int)

plt.bar(x, y, width=(0.7*2*dt).days, color='#A90000')
plt.gca().xaxis.set_major_locator(mdates.WeekdayLocator(mdates.SU, interval=1))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%d %b %Y"))
plt.show()

在此处输入图片说明

Now the labels correspond to actual dates which can be formatted in a desired way.现在标签对应于可以以所需方式格式化的实际日期。 You'll notice that the dates here are from 1900 such that we needed to show the labels on every sunday (As the 7th of january 1900 was a sunday).您会注意到这里的日期是从 1900 年开始的,因此我们需要在每个星期日显示标签(因为 1900 年 1 月 7 日是星期日)。 You may want to add the real year to your data, such that this plot becomes correct.您可能希望将真实年份添加到您的数据中,以便该图变得正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何消除 Matplotlib 条形图中条形之间的间隙 - How to remove gaps between bars in Matplotlib bar chart 如何在Matplotlib条形图中删除宽度不等的条之间的间隙 - How to remove gaps between bars with unequal widths in Matplotlib bar chart 如何确定matplotlib条形图中条形的顺序 - How to determine the order of bars in a matplotlib bar chart 如何将第二个轴添加到 matplotlib/seaborn 条形图并使次要点与正确的条形对齐? - How do I add a second axis to a matplotlib/seaborn bar chart and have the secondary points align with the correct bars? 如何在彼此下方的两个不同轴上对齐条形图和折线图的 matplotlib x-ticks? - How do I align matplotlib x-ticks of a bar chart and line chart in two different axes underneath of each other? Matplotlib条形图仅在非零条形图中显示x点 - Matplotlib bar chart show x-ticks only at non-zero bars 无法在Python中的matplotlib条形图中的条形之间产生间隙 - Not able to produce gaps between bars in matplotlib bar chart in Python matplotlib条形图中条形之间的空间太大 - Too much space between bars in matplotlib bar chart 如何避免在matplotlib中的多条形图中的条形重叠 - How do I avoid overlap between bars in a multi-bar chart in matplotlib 如何控制条形图中条形之间的距离 - How to control distance between bars in bar chart
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM