简体   繁体   English

Matplotlib Xticks条形图中的值

[英]Matplotlib Xticks Values in Bar Chart

I have this code and im trying to make a graph. 我有这个代码,我试图制作一个图表。 All values are in the lists are correct. 列表中的所有值都是正确的。 However, i have problem in x axis. 但是,我在x轴上有问题。 First, there is a gap between first two ticks. 首先,前两个刻度之间存在差距。 I read all matplotlib in their site but couldn find anyting useful for this problem. 我在他们的网站上阅读了所有matplotlib,但却找不到任何有用的问题。 I'm all confused about xticks function. 我对xticks功能感到困惑。 This is my graph 这是我的图表

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()

I have tried this line but everything went worse. 我试过这条线,但一切都变得更糟。

plt.xticks(range(all_years),all_years, rotation = '65')

I also want that two bars to be beside not overlap. 我还希望旁边的两个条不重叠。 Just like this : 像这样 : 酒吧并排 Bars side-by-side 酒吧并排

My variables are: 我的变量是:

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

Here is an example how to solve your problem. 以下是如何解决问题的示例。 As you don't provide the data, I first generate some random data in the example below and then visualise it as a bar plot like you requested: 由于您不提供数据,我首先在下面的示例中生成一些随机数据,然后将其可视化为您请求的条形图:

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()

The result looks like this: 结果如下:

提供的代码的结果

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM