条形图中的Matplotlib Xticks值

Mar*_* M. 2 python matplotlib bar-chart

我有这段代码,即时通讯试图做一个图。列表中的所有值均正确。但是,我在x轴上有问题。首先,前两个刻度之间存在间隙。我在他们的网站上阅读了所有的matplotlib,但找不到对这个问题有用的任何东西。我对xticks函数感到困惑。这是我的图

plt.bar(Valloc1,[diabete[w] for w in sorted(diabete.keys())], width=0.2,)

plt.bar(Valloc2,[not_diabete[w] for w in sorted(not_diabete.keys())], width=0.1, )

plt.xticks(all_years, rotation = '65')
plt.legend(['Diabete','Not-Diabete'])
plt.xlabel('Years')
plt.ylabel('# of patients')
plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这条线,但是一切都变糟了。

plt.xticks(range(all_years),all_years, rotation = '65')
Run Code Online (Sandbox Code Playgroud)

我也希望两个条形不重叠。像这样 : 并排的酒吧 并排的酒吧

我的变量是:

Valloc1 = [i for i in range(52)]
diabete = {{1967: 5, 1986: 13, 1985: 9, 1996: 5, 1984: 10, 1987: 6, 1991: 8...}
Run Code Online (Sandbox Code Playgroud)

Tho*_*ühn 7

这是解决问题的示例。由于您没有提供数据,因此我首先在下面的示例中生成一些随机数据,然后按照您的要求将其可视化为条形图:

from matplotlib import pyplot as plt
import numpy as np

##generating some data
years = [1936, 1945]+[i for i in range(1947,1997)]
data1 = np.random.rand(len(years))
data2 = np.random.rand(len(years))

diabete = {key: val for key,val in zip(years, data1)}
not_diabete = {key: val for key,val in zip(years, data2)}



##the actual graph:
fig, ax = plt.subplots(figsize = (10,4))

idx = np.asarray([i for i in range(len(years))])

width = 0.2

ax.bar(idx, [val for key,val in sorted(diabete.items())], width=width)
ax.bar(idx+width, [val for key,val in sorted(not_diabete.items())], width=width)

ax.set_xticks(idx)
ax.set_xticklabels(years, rotation=65)
ax.legend(['Diabete', 'Non-Diabete'])
ax.set_xlabel('years')
ax.set_ylabel('# of patients')

fig.tight_layout()

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果看起来像这样:

提供的代码的结果