Reputation: 61
I would like to plot a relatively simpler bar chart but struggling to plot using Matplotlib. Could I get some help please. I would like to prepare a chart as shown on this Bar Chart. A sample data is shown below for Tests 1, 2 and 3.
I have more than 20 tests results I would like to plot on a big single plot so I would prefer to cycle through color maps if possible.
My working code so far is this. As you can see my attempt is nowhere near what I need.
"""
A B C
Test 1 1 1.5 2.5
Test 2 1.5 2 3.5
Test 3 1 0.5 1.5
"""
from matplotlib import pyplot as plt
import numpy as np
width = 0.2
x = np.arange(3)
#Test 1
val1 = [1, 1.5, 1]
lab1_x = ['A' for i in range(len(val1))]
plt.bar(x, val1, width)
plt.xticks(x, lab1_x)
#Test 2
val2 = [1.5,2,3.5]
lab2_x = ['B' for i in range(len(val2))]
plt.bar(x+width, val2, width)
plt.xticks(x, lab2_x)
#Test 3
val3 = [1,0.5,1.5]
lab3_x = ['C' for i in range(len(val3))]
plt.bar(x+ 2*width, val3, width)
plt.xticks(x, lab3_x)
plt.legend(["Test 1", "Test 2", "Test 3"], loc = 'best')
Upvotes: 3
Views: 1105
Reputation: 61
I managed to get what I needed. Sharing it here if anyone else is interested.
from random import seed
from random import random
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import matplotlib as mpl
# name of colour map
cmap = mpl.cm.tab20c
totaltests = 10
# seed random number generator
seed(2)
A = []
# generate random numbers between 0-1
for _ in range(totaltests):
A.append(2*random())
# seed random number generator
seed(4)
B = []
# generate random numbers between 0-1
for _ in range(totaltests):
B.append(2*random())
# sum of two columns
sumbd = [x + y for x, y in zip(A, B)]
index = np.arange(len(sumbd))
bar_width = 0.3
shift = 0.5 # used to minimise gaps between each Test sets
ticklist = []
for i in ('A','B','C'):
for _ in range(totaltests):
ticklist.append(i)
#print(A)
ticklist = tuple(ticklist)
plt.xticks(np.append(np.append(index-shift , index-shift + bar_width/1), index-shift + 2*bar_width/1), # tick positions
ticklist, # label corresponding to each tick
rotation=0)
color_list = cmap([x for x in range(0,totaltests,1)])
Aplot = plt.bar(index-shift , A, bar_width-0.01, edgecolor ='black', color = color_list)
Bplot = plt.bar(index-shift + bar_width/1, B, bar_width-0.01, edgecolor ='black', color = color_list)
sumbedplot = plt.bar(index-shift +2* bar_width/1, sumbd, bar_width-0.01, edgecolor ='black', color = color_list)
handlesList = ['T'+str(x) for x in range(1,totaltests+1,1)]
# generate all handles for legend
for i in range(0,totaltests,1):
handlesList[i] = mpatches.Patch(color= color_list[i], label = "Test"+str(i+1))
# Rest of plotting
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Fig xxx')
plt.axis("tight")
plt.legend(handles=handlesList, bbox_to_anchor=(1.01, 1.0), loc='upper left')
plt.tight_layout()
plt.show()
Upvotes: 3