Issue
I'm trying to create a plot in matplotlib where I've applied two methods to two datasets, altering the type of fit for each one, so that I have 8 data result points.
This is the code I currently have:
n_groups = 4
means_type1 = (10,20,10,15)
means_type2 = (20,30,15,10)
# create plot
fig, ax = plt.subplots()
plt.grid(which='major', color='#EEEEEE', linewidth=0.5,zorder=0)
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 = plt.bar(index, means_type1, bar_width,
alpha=1,
color='blue',
label='Type 1',zorder=3)
rects2 = plt.bar(index + bar_width, means_type2, bar_width,
alpha=1,
color='green',
label='Type 2',zorder=3)
plt.ylabel('Metric')
plt.xticks(index + bar_width, ('Dataset 1', 'Dataset 2', 'Dataset 1', 'Dataset 2'))
plt.legend()
plt.figtext(0.4,0.01, "Method 1", ha="center", va="center",fontsize=7)
plt.figtext(0.77,0.01, "Method 2", ha="center", va="center",fontsize=7)
plt.tight_layout()
plt.show()
which generates the plot:
The plot is mostly what I'm after, but there are two key changes I can't seem to make:
- The labels for the dataset aren't centered - they're centered around just Type 2. This is also the case for the x-axis tick.
- The method labels aren't centered, I've put them approximately in the middle.
- I'd like some way to separate the methods. Something like a vertical line going down from the x-axis to split it up a bit.
Solution
- Tick alignment: set
align='edge'
inbar
. - Method label alignment: use
annotate
to place the labels with different coordinate systems for the x and y locations. Here I use figure fraction for the y values to be consistent with what you got fromplt.figtext
, but data coordinates for the x-values. - Vertical line: use
ax.vline
.
Note that having set align='edge'
in bar
, the left edges of your blue bars are at the index
values. So the line and "Method" annotations are 0.15 less than that in the x-direction.
import matplotlib.pyplot as plt
import numpy as np
n_groups = 4
means_type1 = (10,20,10,15)
means_type2 = (20,30,15,10)
# create plot
fig, ax = plt.subplots()
plt.grid(which='major', color='#EEEEEE', linewidth=0.5,zorder=0)
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 = plt.bar(index, means_type1, bar_width,
alpha=1,
color='blue',
label='Type 1',zorder=3, align='edge')
rects2 = plt.bar(index + bar_width, means_type2, bar_width,
alpha=1,
color='green',
label='Type 2',zorder=3, align='edge')
ax.axvline(index[2] - 0.15, color='gray', linestyle='dashed')
plt.ylabel('Metric')
plt.xticks(index + bar_width, ('Dataset 1', 'Dataset 2', 'Dataset 1', 'Dataset 2'))
plt.legend()
ax.annotate("Method 1", (index[1] - 0.15, 0.01), xycoords=('data', 'figure fraction'), ha="center", va="center",fontsize=7)
ax.annotate("Method 2", (index[3] - 0.15, 0.01), xycoords=('data', 'figure fraction'), ha="center", va="center",fontsize=7)
plt.tight_layout()
plt.show()
Answered By - RuthC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.