Reputation: 477
I want make 2 charts with space if I write:
x_axis_1 = ['A','B','C']
y_axis_1 = [5,10,15]
y_axis_2 = [7,3,4]
plt.figure(figsize = (15,6))
plt.bar(x_axis_1-0.2, y_axis_1)
plt.bar(x_axis_1+0.2, y_axis_2)
plt.show()
I get
TypeError: unsupported operand type(s) for -: 'list' and 'float'
because x_axis
is strings
How I can change this ?
Upvotes: 0
Views: 137
Reputation: 474
You mean like this?
import matplotlib.pyplot as plt
# You can use this to create a figure and axes in one line
# If you want to make 4 plots in a square configuration you'd need
# fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2,figsize=(15,6))
# Google how to do multiplots in matplotlib.
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2,figsize=(15,6))
x_axis_1 = ['A','B','C']
y_axis_1 = [5,10,15]
y_axis_2 = [7,3,4]
ax1.bar(x_axis_1, y_axis_1)
ax2.bar(x_axis_1, y_axis_2)
plt.show()
PS: Include import
statements in your code. It's annoying to have to look what modules you are using myself.
PSS: using minus on a python list never works, even if it is filled with numbers. If you want to do that sort of thing you need numpy arrays:
import numpy as np
array = np.array([1,2,3,2,1])
print(array-0.2)
EDITED CORRECT VERSION:
So this is it:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(15,6))
# you need to define a bar width for alignment later on
bar_width = 0.35
# Those are just labels, not the positions
x_axis_labels = ['A','B','C']
# Those are just positions, not labels
x_axis_1 = np.arange(len(x_axis_labels))
y_axis_1 = np.array([5,10,15])
y_axis_2 = np.array([7,3,4])
ax.bar(x_axis_1, y_axis_1,bar_width)
ax.bar(x_axis_1+bar_width, y_axis_2,bar_width)
# This sets the number of ticks to the number of labels.
# It also aligns the tick positions with the center of the bars. Notice the + bar_width/2
ax.set_xticks(np.arange(len(x_axis_labels))+bar_width/2)
# This sets the three ticks, which are now at the right positions, to your x_axis_labels
ax.set_xticklabels(x_axis_labels)
plt.show()
PSSS: Try to formulate your questions more accurately. I had a hard time understanding what you meant. Also this question is a double of this question:Python Create Bar Chart Comparing 2 sets of data .
PSSSS: Karma plz. I want to reach 420 Points.
Upvotes: 0
Reputation: 39072
Your x_axis_1
is a list of strings so you get this error. You need to pass numeric values for the positioning of bars. I have used -0.1
and +0.1
to have the bars placed adjacently.
plt.bar(np.arange(3)-0.1, y_axis_1, width=0.2, align='center')
plt.bar(np.arange(3)+0.1, y_axis_2, width=0.2, align='center')
plt.xticks(range(3), x_axis_1)
Upvotes: 2