Title, xlabel and y label don't appear in bar plot

Viewed 39

I am trying to make a bar plot, where I have 4 bars per dataset and 4 datasets in total. My problem is that my code doesn't show the title, the label in y axis and name of datasets in x axis (G1,G2,G3,G4). Here is a reproductible, minimal code that shows what i'm trying to do.

import numpy as np
import matplotlib.pyplot as plt





test = np.arange(4)+1
data = [test, test, test, test]
err = np.linspace(0.1,0.2,4)
X = np.arange(4) 
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

ax.bar(X + 0, data[0], color = 'lightblue', width = 0.2, yerr=err, ecolor="darkgray")
ax.bar(X + 0.2, data[1], color = 'limegreen', width = 0.2, yerr=err, ecolor="darkgray")
ax.bar(X + 0.4, data[2], color = 'r', width = 0.2, yerr=err, ecolor="darkgray")
ax.bar(X + 0.6, data[3], color = 'y', width = 0.2, yerr=err, ecolor="darkgray")

ax.legend(labels=['shrink', 'uniform','insert','replace'])
ax.set_ylabel('Mutation rates')
ax.set_title('Mutation rates variation by dataset')
ax.set_xticks([0, 0.2, 0.4, 0.6], ('G1', 'G2', 'G3', 'G4'))
plt.show()

Here is what I get as a result: enter image description here

Any help or hint of what i'm doing wrong would be appreciated!

1 Answers

The problem was with the fig = plt.figure() and ax = fig.add_axes([0,0,1,1]) lines. I changed them to fig, ax = plt.subplots().

import numpy as np
import matplotlib.pyplot as plt

test = np.arange(4)+1
data = [test, test, test, test]
err = np.linspace(0.1,0.2,4)
X = np.arange(4) 
fig, ax = plt.subplots()

ax.bar(X + 0, data[0], color = 'lightblue', width = 0.2, yerr=err, ecolor="darkgray")
ax.bar(X + 0.2, data[1], color = 'limegreen', width = 0.2, yerr=err, ecolor="darkgray")
ax.bar(X + 0.4, data[2], color = 'r', width = 0.2, yerr=err, ecolor="darkgray")
ax.bar(X + 0.6, data[3], color = 'y', width = 0.2, yerr=err, ecolor="darkgray")

ax.legend(labels=['shrink', 'uniform','insert','replace'])
ax.set_ylabel('Mutation rates')
ax.set_title('Mutation rates variation by dataset')
ax.set_xticks([0.3, 1.3, 2.3, 3.3])
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4'))

plt.show()

Output

enter image description here

I also corrected some issue with ax.set_xticks that will be deprecated.

Related