I have a pie chart drawing the values extracted from a CSV file. The proportion of the values are currently displayed with the percentage displayed "autopct='%1.1f%%'". Is there a way to display the actual values which are represented in the dataset for each slice.
#Pie for Life Expectancy in Boroughs
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
# show plots inline
%matplotlib inline
# use ggplot style
matplotlib.style.use('ggplot')
#read data
lifeEx = pd.read_csv('LEpie.csv')
#Select columns
df = pd.DataFrame()
df['LB'] = lifeEx[['Regions']]
df['LifeEx'] = lifeEx[['MinLF']]
colorz = ['#B5DF00','#AD1FFF', '#BF1B00','#5FB1FF','#FFC93F']
exploda = (0, 0, 0, 0.1, 0)
#plotting
plt.pie(df['LifeEx'], labels=df['LB'], colors=colorz, autopct='%1.1f%%', explode = exploda, shadow = True,startangle=90)
#labeling
plt.title('Min Life expectancy across London Regions', fontsize=12)
Using the autopct keyword
As we know that the percentage shown times the sum of all actual values must be the actual value, we can define this as a function and supply this function to plt.pie using the autopct keyword.
import matplotlib.pyplot as plt
import numpy
labels = 'Frogs', 'Hogs', 'Dogs'
sizes = numpy.array([5860, 677, 3200])
colors = ['yellowgreen', 'gold', 'lightskyblue']
def absolute_value(val):
a = numpy.round(val/100.*sizes.sum(), 0)
return a
plt.pie(sizes, labels=labels, colors=colors,
autopct=absolute_value, shadow=True)
plt.axis('equal')
plt.show()
Care must be taken since the calculation involves some error, so the supplied value is only accurate to some decimal places.
A little bit more advanced may be the following function, that tries to get the original value from the input array back by comparing the difference between the calculated value and the input array. This method does not have the problem of inaccuracy but relies on input values which are sufficiently distinct from one another.
def absolute_value2(val):
a = sizes[ numpy.abs(sizes - val/100.*sizes.sum()).argmin() ]
return a
Changing text after pie creation
The other option is to first let the pie being drawn with the percentage values and replace them afterwards. To this end, one would store the autopct labels returned by plt.pie() and loop over them to replace the text with the values from the original array. Attention, plt.pie() only returns three arguments, the last one being the labels of interest, when autopct keyword is provided so we set it to an empty string here.
labels = 'Frogs', 'Hogs', 'Dogs'
sizes = numpy.array([5860, 677, 3200])
colors = ['yellowgreen', 'gold', 'lightskyblue']
p, tx, autotexts = plt.pie(sizes, labels=labels, colors=colors,
autopct="", shadow=True)
for i, a in enumerate(autotexts):
a.set_text("{}".format(sizes[i]))
plt.axis('equal')
plt.show()
If you're looking to plot a piechart from a DataFrame, and want to display the actual values instead of percentages, you could reformat autopct like so:
values=df['your_column'].value_counts(dropna=True)
plt.pie(<actual_values>, colors = colors, autopct= lambda x: '{:.0f}'.format(x*values.sum()/100), startangle=90)
The example below creates a Donut, but you could play around:
(Credit to Kevin Amipara # https://medium.com/#kvnamipara/a-better-visualisation-of-pie-charts-by-matplotlib-935b7667d77f)
import matplotlib.pyplot as plt
# Pie chart (plots value counts in this case)
labels = df['your_column'].dropna().unique()
actual_values = df['your_column'].value_counts(dropna=True)
#choose your colors
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#fffd55']
fig1, ax1 = plt.subplots()
# To denote actual values instead of percentages as labels in the pie chart, reformat autopct
values=df['your_column'].value_counts(dropna=True)
plt.pie(actual_values, colors = colors, autopct= lambda x: '{:.0f}'.format(x*values.sum()/100), startangle=90)
#draw circle (this example creates a donut)
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
# Equal aspect ratio ensures that pie is drawn as a circle
ax1.axis('equal')
# A separate legend with labels (drawn to the bottom left of the pie in this case)
plt.legend(labels, bbox_to_anchor = (0.1, .3))
plt.tight_layout()
plt.show()
Related
I'm creating a bar chart, and I can't figure out how to add value labels on the bars (in the center of the bar, or just above it).
I believe the solution is either with 'text' or 'annotate', but I:
a) don't know which one to use (and generally speaking, haven't figured out when to use which).
b) can't see to get either to present the value labels.
Here is my code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.mpl_style', 'default')
%matplotlib inline
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
fig = freq_series.plot(kind='bar')
fig.set_title('Amount Frequency')
fig.set_xlabel('Amount ($)')
fig.set_ylabel('Frequency')
fig.set_xticklabels(x_labels)
How can I add value labels on the bars (in the center of the bar, or just above it)?
Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)
x_labels = [
108300.0,
110540.0,
112780.0,
115020.0,
117260.0,
119500.0,
121740.0,
123980.0,
126220.0,
128460.0,
130700.0,
]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind="bar")
ax.set_title("Amount Frequency")
ax.set_xlabel("Amount ($)")
ax.set_ylabel("Frequency")
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = [f"label{i}" for i in range(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2, height + 5, label, ha="center", va="bottom"
)
plt.show()
This produces a labeled plot that looks like:
Based on a feature mentioned in this answer to another question I have found a very generally applicable solution for placing labels on a bar chart.
Other solutions unfortunately do not work in many cases, because the spacing between label and bar is either given in absolute units of the bars or is scaled by the height of the bar. The former only works for a narrow range of values and the latter gives inconsistent spacing within one plot. Neither works well with logarithmic axes.
The solution I propose works independent of scale (i.e. for small and large numbers) and even correctly places labels for negative values and with logarithmic scales because it uses the visual unit points for offsets.
I have added a negative number to showcase the correct placement of labels in such a case.
The value of the height of each bar is used as a label for it. Other labels can easily be used with Simon's for rect, label in zip(rects, labels) snippet.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
def add_value_labels(ax, spacing=5):
"""Add labels to the end of each bar in a bar chart.
Arguments:
ax (matplotlib.axes.Axes): The matplotlib object containing the axes
of the plot to annotate.
spacing (int): The distance between the labels and the bars.
"""
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
y_value = rect.get_height()
x_value = rect.get_x() + rect.get_width() / 2
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
va = 'bottom'
# If value of bar is negative: Place label below bar
if y_value < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
# Use Y value as label and format number with one decimal place
label = "{:.1f}".format(y_value)
# Create annotation
ax.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(0, space), # Vertically shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
ha='center', # Horizontally center label
va=va) # Vertically align label differently for
# positive and negative values.
# Call the function above. All the magic happens there.
add_value_labels(ax)
plt.savefig("image.png")
Edit: I have extracted the relevant functionality in a function, as suggested by barnhillec.
This produces the following output:
And with logarithmic scale (and some adjustment to the input data to showcase logarithmic scaling), this is the result:
As of matplotlib v3.4.0
Use matplotlib.pyplot.bar_label
The default label position, set with the parameter label_type, is 'edge'. To center the labels in the middle of the bar, use 'center'
Additional kwargs are passed to Axes.annotate, which accepts Text kwargs.
Properties like color, rotation, fontsize, etc., can be used.
See the matplotlib: Bar Label Demo page for additional formatting options.
Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2
ax.containers is a list of BarContainer artists
With a single level bar plot, it's a list of len 1, hence [0] is used.
For grouped and stacked bar plots there will be more objects in the list
Stacked
Grouped
How to annotate each segment of a stacked bar chart
How to plot and annotate grouped bars in seaborn
Stacked Bar Chart with Centered Labels
How to plot and annotate a grouped bar chart
Simple label formatting can be done with the fmt parameter, as shown in the Demo examples and at How to annotate a seaborn barplot with the aggregated value.
More sophisticated label formatting should use the label parameter, as shown in the Demo examples and the following
Examples with label=
Examples with label=
stack bar plot in matplotlib and add label to each section
How to annotate a stacked bar plot and add legend labels
How to add multiple annotations to a barplot
How to customize bar annotations to not show selected values
How to plot a horizontal stacked bar with annotations
How to annotate bar plots when adding error bars
How to align annotations at the end of a horizontal bar plot
import pandas as pd
# dataframe using frequencies and x_labels from the OP
df = pd.DataFrame({'Frequency': frequencies}, index=x_labels)
# display(df)
Frequency
108300.0 6
110540.0 16
112780.0 75
115020.0 160
117260.0 244
# plot
ax = df.plot(kind='bar', figsize=(12, 8), title='Amount Frequency',
xlabel='Amount ($)', ylabel='Frequency', legend=False)
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)
Specify additional kwargs for additional customization
Accepts parameters from matplotlib.axes.Axes.text
ax.bar_label(ax.containers[0], label_type='edge', color='red', rotation=90, fontsize=7, padding=3)
Seaborn axes-level plot
As can be seen, the is exactly the same as with ax.bar(...), plt.bar(...), and df.plot(kind='bar',...)
import seaborn as sns
# plot data
fig, ax = plt.subplots(figsize=(12, 8))
sns.barplot(x=x_labels, y=frequencies, ax=ax)
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)
Seaborn figure-level plot
seaborn.catplot accepts a dataframe for data.
Since .catplot is a FacetGrid (subplots), the only difference is to iterate through each axes of the figure to use .bar_labels.
import pandas as pd
import seaborn as sns
# load the data into a dataframe
df = pd.DataFrame({'Frequency': frequencies, 'amount': x_labels})
# plot
g = sns.catplot(kind='bar', data=df, x='amount', y='Frequency', height=6, aspect=1.5)
# iterate through the axes
for ax in g.axes.flat:
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure; should be in the loop, otherwise only the last subplot would be adjusted
ax.margins(y=0.1)
matplotlib.axes.Axes.bar
It will be similar if just using matplotlib.pyplot.bar
import matplotlib.pyplot as plt
# create the xticks beginning a index 0
xticks = range(len(frequencies))
# plot
fig, ax = plt.subplots(figsize=(12, 8))
ax.bar(x=xticks, height=frequencies)
# label the xticks
ax.set_xticks(xticks, x_labels)
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)
Other examples using bar_label
Linked SO Answers
Linked SO Answers
How to create and annotate a stacked proportional bar chart
How to wrap long tick labels in a seaborn figure-level plot
How to calculate percent by row and annotate 100 percent stacked bars
How to annotate barplot with percent by hue/legend group
Stacked bars are unexpectedly annotated with the sum of bar heights
How to add percentages on top of bars in seaborn
How to plot and annotate grouped bars
How to plot percentage with seaborn distplot / histplot / displot
How to annotate bar chart with values different to those from get_height()
How to plot grouped bars in the correct order
Pandas bar how to label desired values
Problem with plotting two lists with different sizes using matplotlib
How to display percentage above grouped bar chart
How to annotate only one category of a stacked bar plot
How to set ticklabel rotation and add bar annotations
How to Increase subplot text size and add custom bar plot annotations
How to aggregate group metrics and plot data with pandas
How to get a grouped bar plot of categorical data
How to plot a stacked bar with annotations for multiple groups
How to create grouped bar plots in a single figure from a wide dataframe
How to annotate a stackplot or area plot
How to determine if the last value in all columns is greater than n
How to plot grouped bars
How to plot element count and add annotations
How to add multiple data labels in a bar chart in matplotlib
Seaborn Catplot set values over the bars
Python matplotlib multiple bars
Matplotlib pie chart label does not match value
plt grid ALPHA parameter not working in matplotlib
How to horizontally center a bar plot annotation
Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
freq_series = pd.Series(frequencies)
y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read
rects = ax.patches
# For each bar: Place a label
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'
# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'
# Use X value as label and format number with one decimal place
label = "{:.1f}".format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(space, 0), # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha) # Horizontally align label differently for
# positive and negative values.
plt.savefig("image.png")
If you want to just label the data points above the bar, you could use plt.annotate()
My code:
import numpy as np
import matplotlib.pyplot as plt
n = [1,2,3,4,5,]
s = [i**2 for i in n]
line = plt.bar(n,s)
plt.xlabel('Number')
plt.ylabel("Square")
for i in range(len(s)):
plt.annotate(str(s[i]), xy=(n[i],s[i]), ha='center', va='bottom')
plt.show()
By specifying a horizontal and vertical alignment of 'center' and 'bottom' respectively one can get centered annotations.
I needed the bar labels too, note that my y-axis is having a zoomed view using limits on y axis. The default calculations for putting the labels on top of the bar still works using height (use_global_coordinate=False in the example). But I wanted to show that the labels can be put in the bottom of the graph too in zoomed view using global coordinates in matplotlib 3.0.2. Hope it help someone.
def autolabel(rects,data):
"""
Attach a text label above each bar displaying its height
"""
c = 0
initial = 0.091
offset = 0.205
use_global_coordinate = True
if use_global_coordinate:
for i in data:
ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,fontsize=8)
c=c+1
else:
for rect,i in zip(rects,data):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')
If you only want to add Datapoints above the bars, you could easily do it with:
for i in range(len(frequencies)): # your number of bars
plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument
y = y_values[i]+1, #takes your y values as vertical positioning argument
s = data_labels[i], # the labels you want to add to the data
size = 9) # font size of datalabels
I have a sample dataset as follows;
pd.DataFrame({'Day_Duration':['Evening','Evening','Evening','Evening','Evening','Morning','Morning','Morning',
'Morning','Morning','Night','Night','Night','Night','Night','Noon','Noon','Noon',
'Noon','Noon'],'place_category':['Other','Italian','Japanese','Chinese','Burger',
'Other','Juice Bar','Donut','Bakery','American','Other','Italian','Japanese','Burger',\
'American','Other','Italian','Burger','American','Salad'],'Percent_delivery':[14.03,10.61,9.25,8.19,6.89,19.58,10.18,9.14,8.36,6.53,13.60,8.42,\
8.22,7.66,6.67,17.71,10.62,8.44,8.33,7.50]})
The goal is to draw faceted barplot with Day_duration serving as facets, hence 4 facets in total. I used the following code to achieve the same,
import seaborn as sns
#g = sns.FacetGrid(top5_places, col="Day_Duration")
g=sns.catplot(x="place_category", y="Percent_delivery", hue='place_category',col='Day_Duration',\
data=top5_places,ci=None,kind='bar',height=4, aspect=.7)
g.set_xticklabels(rotation=90)
Attached is the figure I got;
Can I kindly get help with 2 things, first is it possible to get only 5 values on the x-axis for each facet(rather than seeing all the values for each facet), second, is there a way to make the bars a bit wider. Help is appreciated.
Because you're using hue the api applies a unique color to each value of place_category, but it also expects each category to be in the plot, as shown in your image.
The final figure is a FacetGrid. Using subplot is the manual way of creating one.
In order to plot only the top n categories for each Day_Duration, each plot will need to be done individually, with a custom color map.
cmap is a dictionary with place categories as keys and colors as values. It's used so there will be one legend and each category will be colored the same for each plot.
Because we're not using the legend automatically generated by the plot, one needs to be created manually.
patches uses Patch to create each item in the legend. (e.g. the rectangle, associated with color and name).
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
# create a color map for unique values or place
place_cat = df.place_category.unique()
colors = sns.color_palette('husl', n_colors=10)
cmap = dict(zip(place_cat, colors))
# plot a subplot for each Day_Duration
plt.figure(figsize=(16, 6))
for i, tod in enumerate(df.Day_Duration.unique(), 1):
data = df[df.Day_Duration == tod].sort_values(['Percent_delivery'], ascending=False)
plt.subplot(1, 4, i)
p = sns.barplot(x='place_category', y='Percent_delivery', data=data, hue='place_category', palette=cmap)
p.legend_.remove()
plt.xticks(rotation=90)
plt.title(f'Day Duration: {tod}')
plt.tight_layout()
patches = [Patch(color=v, label=k) for k, v in cmap.items()]
plt.legend(handles=patches, bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0)
plt.show()
I would like to plot a pie chart that shows contributions that are more than 1%, and their corresponding legend label.
I have managed showing the percentage values I wanted on the pie (see script below), but not the legend labels. In the following example, I want to show legend labels ABCD, but not EF.
I have tried several things, but only able to show either a full legend, or a filtered legend with unmatched (wrong) colors.
How can I do this? Can someone help? Thanks.
sizes = pd.DataFrame([80,10,5,4,0.1,0.9],index=list("ABCDEF"))
fig1, ax2 = plt.subplots()
def autopct_more_than_1(pct):
return ('%1.f%%' % pct) if pct > 1 else ''
ax2.pie(sizes.values, autopct=autopct_more_than_1)
ax2.axis('equal')
plt.legend(sizes.index, loc="best", bbox_to_anchor=(1,1))
plt.show()
You can loop over the dataframe values (possibly normalized if they aren't already) and only take the legend handles and labels for those which are bigger than 1.
import matplotlib.pyplot as plt
import pandas as pd
sizes = pd.DataFrame([80,10,5,4,0.1,0.9],index=list("ABCDEF"))
fig1, ax = plt.subplots()
def autopct_more_than_1(pct):
return ('%1.f%%' % pct) if pct > 1 else ''
p,t,a = ax.pie(sizes.values, autopct=autopct_more_than_1)
ax.axis('equal')
# normalize dataframe (not actually needed here, but for general case)
normsizes = sizes/sizes.sum()*100
# create handles and labels for legend, take only those where value is > 1
h,l = zip(*[(h,lab) for h,lab,i in zip(p,sizes.index.values,normsizes.values) if i > 1])
ax.legend(h, l,loc="best", bbox_to_anchor=(1,1))
plt.show()
Is there a way to add a secondary legend to a scatterplot, where the size of the scatter is proportional to some data?
I have written the following code that generates a scatterplot. The color of the scatter represents the year (and is taken from a user-defined df) while the size of the scatter represents variable 3 (also taken from a df but is raw data):
import pandas as pd
colors = pd.DataFrame({'1985':'red','1990':'b','1995':'k','2000':'g','2005':'m','2010':'y'}, index=[0,1,2,3,4,5])
fig = plt.figure()
ax = fig.add_subplot(111)
for i in df.keys():
df[i].plot(kind='scatter',x='variable1',y='variable2',ax=ax,label=i,s=df[i]['variable3']/100, c=colors[i])
ax.legend(loc='upper right')
ax.set_xlabel("Variable 1")
ax.set_ylabel("Variable 2")
This code (with my data) produces the following graph:
So while the colors/years are well and clearly defined, the size of the scatter is not.
How can I add a secondary or additional legend that defines what the size of the scatter means?
You will need to create the second legend yourself, i.e. you need to create some artists to populate the legend with. In the case of a scatter we can use a normal plot and set the marker accordingly.
This is shown in the below example. To actually add a second legend we need to add the first legend to the axes, such that the new legend does not overwrite the first one.
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np; np.random.seed(1)
import pandas as pd
plt.rcParams["figure.subplot.right"] = 0.8
v = np.random.rand(30,4)
v[:,2] = np.random.choice(np.arange(1980,2015,5), size=30)
v[:,3] = np.random.randint(5,13,size=30)
df= pd.DataFrame(v, columns=["x","y","year","quality"])
df.year = df.year.values.astype(int)
fig, ax = plt.subplots()
for i, (name, dff) in enumerate(df.groupby("year")):
c = matplotlib.colors.to_hex(plt.cm.jet(i/7.))
dff.plot(kind='scatter',x='x',y='y', label=name, c=c,
s=dff.quality**2, ax=ax)
leg = plt.legend(loc=(1.03,0), title="Year")
ax.add_artist(leg)
h = [plt.plot([],[], color="gray", marker="o", ms=i, ls="")[0] for i in range(5,13)]
plt.legend(handles=h, labels=range(5,13),loc=(1.03,0.5), title="Quality")
plt.show()
Have a look at http://matplotlib.org/users/legend_guide.html.
It shows how to have multiple legends (about halfway down) and there is another example that shows how to set the marker size.
If that doesn't work, then you can also create a custom legend (last example).
Is there a way to change the color of the violin plots in matplotlib?
The default color is this "brownish" color, which is not too bad, but I'd like to color e.g., the first 3 violins differently to highlight them. I don't find any parameter in the documentation. Any ideas or hacks to color the violins differently?
matplotlib.pyplot.violinplot() says it returns:
A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys:
bodies: A list of the matplotlib.collections.PolyCollection instances containing the filled area of each violin.
[...among others...]
Methods of PolyCollections include:
set_color(c) which sets both the facecolor and edgecolor,
set_facecolor(c) and
set_edgecolor(c) all of which take a "matplotlib color arg or sequence of rgba tuples"
So, it looks like you could just loop through the result's body list and modify the facecolor of each:
violin_parts = plt.violinplot(...)
for pc in violin_parts['bodies']:
pc.set_facecolor('red')
pc.set_edgecolor('black')
It is a bit strange though that you can't set this when creating it like the common plot types. I'd guess it's probably because the operation creates so many bits (the aforementioned PolyCollection along with 5 other LineCollections), that additional arguments would be ambiguous.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
rrred = '#ff2222'
bluuu = '#2222ff'
x = np.arange(2, 25)
y = np.array([xi * np.random.uniform(0, 1, 10**3) for xi in x]).T
# Create violin plot objects:
fig, ax = plt.subplots(1, 1, figsize = (8,8))
violin_parts = ax.violinplot(y, x, widths = 0.9, showmeans = True, showextrema = True, showmedians = True)
# Make all the violin statistics marks red:
for partname in ('cbars','cmins','cmaxes','cmeans','cmedians'):
vp = violin_parts[partname]
vp.set_edgecolor(rrred)
vp.set_linewidth(1)
# Make the violin body blue with a red border:
for vp in violin_parts['bodies']:
vp.set_facecolor(bluuu)
vp.set_edgecolor(rrred)
vp.set_linewidth(1)
vp.set_alpha(0.5)
Suppose you have 3 vectors: data1, data2, data3; and you have plotted your matplotlib violinplots in one figure; then, to set the color of the median line and body facecolor specific for each sub-violinplot you can use:
colors = ['Blue', 'Green', 'Purple']
# Set the color of the violin patches
for pc, color in zip(plots['bodies'], colors):
pc.set_facecolor(color)
# Set the color of the median lines
plots['cmedians'].set_colors(colors)
The full example:
# Set up the figure and axis
fig, ax = plt.subplots(1, 1)
# Create a list of the data to be plotted
data = [data1, data2, data3]
# Set the colors for the violins based on the category
colors = ['Blue', 'Green', 'Purple']
# Create the violin plot
plots = ax.violinplot(data, vert=False, showmedians=True, showextrema=False, widths=1)
# Set the color of the violin patches
for pc, color in zip(plots['bodies'], colors):
pc.set_facecolor(color)
# Set the color of the median lines
plots['cmedians'].set_colors(colors)
# Set the labels
ax1.set_yticks([1, 2, 3], labels=['category1', 'category2', 'category3'])
ax1.invert_yaxis() # ranking from top to bottom: invert yaxis
plt.show()