Issue
I have several subplots with a shared axis. In each subplot I would like the bar of 'Recall' a certain color, the bar of 'Precision' a certain color and so on. Please see the link below that resulted from following code:
# data
values = list([['nan', 'nan', 0.25, 0.25],
['nan', 'nan', 0.813, 0.413],
['nan', 'nan', 0.13793, 0.793],
[0.5, 0.4666, 0.6666666, 0.75],
[0.725, 0.13, 0.444, 0.5],
[0.33337, 0.7776, 0.53,
0.86],
[0.296, 0.33, 0.68,
0.4722],
[0.158, 0.166, 0.45,
0.3477],
[0.22063, 0.2218, 0.54,
0.7778],
[0.8421, 0.199, 0.57,
0.4333],
[0.36842105, 0.545, 0.386,
0.155567],
[0.62281, 0.23394, 0.46,
0.36667]])
index_1 = ['1', '2', '4', '5']
index_2 = ['Recall', 'Precision', 'F1']
iterables = [index_1, index_2]
index = pd.MultiIndex.from_product(iterables, names=["ClusterID", "Metric"])
df = pd.DataFrame(values, columns = ['Method1', 'Method2', 'Method3', 'Method4'], index = index)
c = ['red', 'yellow', 'black']
ax = df.unstack(level=0).plot(kind='bar', subplots=True, rot=0, figsize=(20, 18), layout=(4, 4), color = c)
def_ylim = (0.0, 0.8)
plt.setp(ax, ylim = def_ylim)
plt.tight_layout(pad=0.6, w_pad=0.6, h_pad=1.0)
How could I achieve this? My dataframe is MultiIndex DataFrame in pandas. I'm trying to prep my results for a presentation and I'm fairly new to plotting.
Thanks for your input!
Solution
Thanks for providing the data. I updated the code so that the colors within each subplot has the 3 colors as you needed. Please see if this is ok. However, the legend is disabled.
import pandas as pd
import matplotlib.pyplot as plt
values = list([['nan', 'nan', 0.25, 0.25],
['nan', 'nan', 0.813, 0.413],
['nan', 'nan', 0.13793, 0.793],
[0.5, 0.4666, 0.6666666, 0.75],
[0.725, 0.13, 0.444, 0.5],
[0.33337, 0.7776, 0.53,
0.86],
[0.296, 0.33, 0.68,
0.4722],
[0.158, 0.166, 0.45,
0.3477],
[0.22063, 0.2218, 0.54,
0.7778],
[0.8421, 0.199, 0.57,
0.4333],
[0.36842105, 0.545, 0.386,
0.155567],
[0.62281, 0.23394, 0.46,
0.36667]])
index_1 = ['1', '2', '4', '5']
index_2 = ['Recall', 'Precision', 'F1']
iterables = [index_1, index_2]
index = pd.MultiIndex.from_product(iterables, names=["ClusterID", "Metric"])
df = pd.DataFrame(values, columns = ['Method1', 'Method2', 'Method3', 'Method4'], index = index)
ax = df.unstack(level=0).plot(kind='bar', subplots=True, rot=0, figsize=(20, 18), layout=(4, 4), legend=False)
labels = df.index.get_level_values(1).unique()
for grow in ax: #For each row of graphs
for grph in grow: #For each graph in the specific row
for p, color in zip(grph.patches, ["red", "yellow", "black"]): #For each bar in graph
p.set_facecolor(color)
# grph.legend(labels) #Enabling this only gives the first row - Recall & Red box
def_ylim = (0.0, 0.8)
plt.setp(ax, ylim = def_ylim)
plt.tight_layout(pad=0.6, w_pad=0.6, h_pad=1.0)
Output graph
Answered By - Redox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.