5
votes

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. First, there is a gap between first two ticks. I read all matplotlib in their site but couldn find anyting useful for this problem. I'm all confused about xticks function. 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 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...}
1
Set the xticks as consecutive numerical values and the actual years only as labels: plt.xticks([i for i in range(len(all_years))], all_years, rotation = '65'). - Thomas Kühn
If you want your bars side by side, you also have to specify x values in the bar plot and shift all x values by a constant in the second bar command. That means, define your xtick positions beforehand (best to use numpy), make the two plots and then adjust the labels. - Thomas Kühn
Yes, first one worked great ! Thank you but i couldnt understand second one. Can you explain it some more? - user8893529
To write an actual answer, I would need to know what your variables are. A Minimal, Complete, and Verifiable example would be really helpful. At least I'd need to know what Valloc1 and Valloc2 are. - Thomas Kühn

1 Answers

14
votes

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:

result of the code provided