Matplotlib customize rank line plot - python

I have the following dataframe where it contains the best equipment in operation ranked by 1 to 300 (1 is the best, 300 is the worst) over a few days (df columns)
Equipment 21-03-27 21-03-28 21-03-29 21-03-30 21-03-31 21-04-01 21-04-02
P01-INV-1-1 1 1 1 1 1 2 2
P01-INV-1-2 2 2 4 4 5 1 1
P01-INV-1-3 4 4 3 5 6 10 10
I would like to customize a line plot (example found here) but I'm having some troubles trying to modify the example code provided:
import matplotlib.pyplot as plt
import numpy as np
def energy_rank(data, marker_width=0.1, color='blue'):
y_data = np.repeat(data, 2)
x_data = np.empty_like(y_data)
x_data[0::2] = np.arange(1, len(data)+1) - (marker_width/2)
x_data[1::2] = np.arange(1, len(data)+1) + (marker_width/2)
lines = []
lines.append(plt.Line2D(x_data, y_data, lw=1, linestyle='dashed', color=color))
for x in range(0,len(data)*2, 2):
lines.append(plt.Line2D(x_data[x:x+2], y_data[x:x+2], lw=2, linestyle='solid', color=color))
return lines
data = ranks.head(4).to_numpy() #ranks is the above dataframe
artists = []
for row, color in zip(data, ('red','blue','green','magenta')):
artists.extend(energy_rank(row, color=color))
fig, ax = plt.subplots()
ax.set_xticklabels(ranks.columns) # set X axis to be dataframe columns
ax.set_xticklabels(ax.get_xticklabels(), rotation=35, fontsize = 10)
for artist in artists:
ax.add_artist(artist)
ax.set_ybound([15,0])
ax.set_xbound([.5,8.5])
When using ax.set_xticklabels(ranks.columns), for some reason, it only plots 5 of the 7 days from ranks columns, removing specifically the first and last values. I tried to duplicate those values but this did not work as well. I end up having this below:
In summary, I would like to know if its possible to do 3 customizations:
input all dates from ranks columns on X axis
revert Y axis. ax.set_ybound([15,0]) is not working. It would make more sense to see the graph starting with 0 on top, since 1 is the most important rank to look at
add labels to the end of each line at the last day (last value on X axis). I could add the little window label, but it often gets really messy when you plot more data, so adding just the text at the end of each line would really make it look cleaner
Please let me know if those customizations are impossible to do and any help is really appreciated! Thank you in advance!

To show all the dates, use plt.xticks() and set_xbound to start at 0. To reverse the y axis, use ax.set_ylim(ax.get_ylim()[::-1]). To set the legends the way you described, you can use annotation and set the coordinates of the annotation at your last datapoint for each series.
fig, ax = plt.subplots()
plt.xticks(np.arange(len(ranks.columns)), list(ranks.columns), rotation = 35, fontsize = 10)
plt.xlabel('Date')
plt.ylabel('Rank')
for artist in artists:
ax.add_artist(artist)
ax.set_ybound([0,15])
ax.set_ylim(ax.get_ylim()[::-1])
ax.set_xbound([0,8.5])
ax.annotate('Series 1', xy =(7.1, 2), color = 'red')
ax.annotate('Series 2', xy =(7.1, 1), color = 'blue')
ax.annotate('Series 3', xy =(7.1, 10), color = 'green')
plt.show()
Here is the plot for the three rows of data in your sample dataframe:

Related

Consistent colour across Matplotlib Groupby Graph

I am attempting to create a scatter pie plot that groups by 2 columns, Column1 & Column 2 where the colour in the pie (if numbers are the same) is decided by Column 3.
See my example below of where I am:
This graph shows Column 1 (y-axis) and Column 2 (x-axis). The colour is dictated by Column 3.
But with the code I use the colours do not stay consistent across graphs and if the same Column 3 appears with a different Column 2 or Column 3 value it assigns it a different colour.
I have attempted using cmaps and manually assigning colours but I cannot keep it consistent across each column 2.
See my current code below:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticks
from matplotlib.font_manager import FontProperties
import numpy as np
def draw_pie(dist,
xpos,
ypos,
size,
color,
ax=None):
if ax is None:
fig, ax = plt.subplots(figsize=(70,60))
# for incremental pie slices
cumsum = np.cumsum(dist)
cumsum = cumsum/ cumsum[-1]
pie = [0] + cumsum.tolist()
for r1, r2 in zip(pie[:-1], pie[1:]):
angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)
x = [0] + np.cos(angles).tolist()
y = [0] + np.sin(angles).tolist()
xy = np.column_stack([x, y])
ax.scatter([xpos], [ypos], marker=xy, s=size,c=color)
return ax
colors = {'Group A':'red', 'Group B':'green', 'Group C':'blue', 'Group D':'yellow', 'Group E':'yellow', 'Group F':'yellow', 'Group G':'yellow', 'Group H':'yellow'}
fig, ax = plt.subplots(figsize=(94,70))
for (x,y), d in dataset.groupby(['Column 1','Column 2']):
dist = d['Column 3'].value_counts()
draw_pie(dist, x, y, 50000, ax=ax,color=dataset['Column 3'].map(colors))
params = {'legend.fontsize': 100}
plt.rcParams.update(params)
#plt.legend(dataset["Column 3"],markerscale=.4,frameon=True,framealpha=1,ncol=3,loc=(0.00, -0.3), bbox_to_anchor=(0.0, 0., 0.5, 1.25),handletextpad=1,markerfirst=True,facecolor='lightgrey',mode='expand',borderaxespad=-16)
ax.yaxis.set_major_locator(mticks.MultipleLocator(1))
full = plt.Rectangle((-0.05, 4.25), 2.10, 2, color='g', alpha=0.15)
partial = plt.Rectangle((-0.05, 2.25), 2.10, 2, color='orange', alpha=0.15)
low = plt.Rectangle((-0.05, 0.25), 2.10, 2, color='r', alpha=0.15)
ax.add_patch(full)
ax.add_patch(partial)
ax.add_patch(low)
plt.xticks(fontsize=120)
plt.yticks(fontsize=100)
plt.ylim([0, 6.75])
plt.tight_layout()
plt.show()
Ideally the output graph based on the data (I will copy in below) should be like the below graph (I have placed a number in each pie to define what colour should be there)
Here is the full data used for the graph:
Column 1 3 2 Colour Group Desired
First Line Group A 6 1
First Line Group A 6 1
First Line Group A 6 1
First Line Group C 6 3
First Line Group B 6 2
First Line Group B 6 2
First Line Group B 6 2
First Line Group A 6 1
First Line Group A 6 1
First Line Group C 6 3
First Line Group A 6 1
Second Line Group A 6 1
Second Line Group A 6 1
Second Line Group A 6 1
Second Line Group C 6 3
Second Line Group B 6 2
Second Line Group B 6 2
Second Line Group B 6 2
Second Line Group A 4.5 1
Second Line Group A 6 1
Second Line Group C 6 3
Second Line Group A 6 1
Third Line Group A 1 1
Third Line Group A 6 1
Third Line Group A 1 1
Third Line Group C 6 3
Third Line Group B 3.5 2
Third Line Group B 3.5 2
Third Line Group B 3.5 2
Third Line Group A 1 1
Third Line Group A 1 1
Third Line Group C 4 3
Third Line Group A 1 1
Additionally I would like to add a label in each section of the pie with the count of distinct(Column 3).
Currently I came up with the following solution to fix the issue with the colours:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticks
from matplotlib.font_manager import FontProperties
import numpy as np
def draw_pie(dist,
xpos,
ypos,
size,
ax=None):
if ax is None:
fig, ax = plt.subplots(figsize=(7,6))
# The colors, corresponding to the values 1, 2 and 3:
# 1 is tab:blue
# 2 is tab:orange
# 3 is tab:green
# Of course, you can change this
colors = ['tab:blue', 'tab:orange', 'tab:green']
# for incremental pie slices
cumsum = np.cumsum(dist)
cumsum = cumsum/ cumsum[-1]
pie = [0] + cumsum.tolist()
for r1, r2, i in zip(pie[:-1], pie[1:], range(0, len(dist))):
# If no counts present, skip this one
if dist[i] == 0:
continue
angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)
x = [0] + np.cos(angles).tolist()
y = [0] + np.sin(angles).tolist()
xy = np.column_stack([x, y])
ax.scatter([xpos], [ypos], marker=xy, s=size, color=colors[i])
return ax
#colors = {'Group A':'red', 'Group B':'green', 'Group C':'blue', 'Group D':'yellow', 'Group E':'yellow', 'Group F':'yellow', 'Group G':'yellow', 'Group H':'yellow'}
# Read dataset
dataset = pd.read_csv('dataset.csv')
fig, ax = plt.subplots(figsize=(9,5))
for (x,y), d in dataset.groupby(['Column 1','Column 2']):
# Only interested in the 'Column 3' column, as this one
# contains the values 1-2-3
d = d['Colour Group Desired']
# Count how often each value (1-2-3) occurs and store
# this in a list (count for value i located at list index
# i-1)
dist = list()
for i in [1,2,3]:
dist.append(d[d==i].count())
# Call your draw_pie function
draw_pie(dist, x, y, 500, ax=ax)
ax.yaxis.set_major_locator(mticks.MultipleLocator(1))
full = plt.Rectangle((-0.05, 4.25), 2.10, 2, color='g', alpha=0.15)
partial = plt.Rectangle((-0.05, 2.25), 2.10, 2, color='orange', alpha=0.15)
low = plt.Rectangle((-0.05, 0), 2.10, 2.25, color='r', alpha=0.15)
ax.add_patch(full)
ax.add_patch(partial)
ax.add_patch(low)
plt.xticks(fontsize=10)
plt.yticks(fontsize=8)
plt.ylim([0, 6.75])
plt.tight_layout()
plt.show()
Small note to start with, I changed all sizes by a factor of 10 such that the plot fits on my screen (e.g. the figsize). You probably want to use your original values again, but this doesn't matter for the question anyway.
The first change I made was to the loop body of the for (x,y), d in dataset.groupby(['Column 1','Column 2']) loop. Instead of using dist = d['Column 3'].value_counts(), I create an empty array. Subsequently, I loop over the values 1, 2 and 3. In each iteration, I check how many rows match the specific value and append the outcome to the list. In this way, I end up with a list of size 3, in which the first element corresponds to the amount of rows that equal 1, the second element corresponds to the amount of rows that equal 2 and the third element corresponds to the amount of rows that equal 3. The advantage is that I can also keep track of values that occur 0 times.
Secondly, I changed the draw_pie function a bit. However, since I do not fully understand the meaning of a group in terms of the colour, I commented out the colors dictionary. It looks as if 1 always corresponds to Group A, 2 always corresponds to Group B and 3 always corresponds to Group C. I made use of this observation and defined another colors variable (in the draw_pie function). Instead of a dictionary, colors is now a list (where the first element corresponds to the value 1, the second element corresponds to the value 2 and the third element corresponds to the value 3). I changed your for loop from for r1, r2 in zip(pie[:-1], pie[1:]) to for r1, r2, i in zip(pie[:-1], pie[1:], range(0, len(dist))). The advantage is that I can now use the iteration variable i to get the proper color from the colors list. In addition, I added a small if statement which checks if there are exactly 0 occurences. If that is the case, I just skip the remainder of the loop and draw nothing (if you don't skip these cases, it will draw a very thin line instead. Try this for yourself by removing it).
If I run the code, I get the following result:
Unfortunately, I was not successful in adding the labels. I tried using the Axes.text method, but I couldn't get the labels to be placed at the proper locations.
Edit
I decided to change the body of the draw_pie function. In this new version, we draw an Axes instance at the desired (xpos, ypos) location. This involves some transformations: first a transformation from data coordinates to display coordinates and subsequently a transformation from display coordinates to figure coordinates. See this tutorial for an explanation. The advantage is that we can now plot a pie chart inside the created axes using the Axes.pie method. This method has some nice options, such as adding labels!
However, there is a catch. Before we start drawing the pie charts, we need to already fix the xlim and the ylim values of the main Axes. If we don't do this (and do it after plotting the pie charts), the pie charts will no longer be located at the proper positions. Therefore, I have moved the code which sets the xlim and ylim values before the first time we call the draw_pie function. I also removed to call to plt.tight_layout(), as this will (unfortunately) also cause the pie charts to no longer be located at the proper locations.
As a small side note, I changed the manner in which the background colors are drawn. Instead of using patches, I now use the Axes.axhspan method. With this method, you can still control the y-locations, but the width will extend infinitely (meaning that the colors remain if you scroll left/right). If you don't want this, you can remove it again :).
See the new version of the code below (I note once more, I changed all sizes such that it fits on my computer screen. You probably want to substitute your original sizes again):
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticks
from matplotlib.font_manager import FontProperties
import numpy as np
def draw_pie(dist,
xpos,
ypos,
size,
ax=None,
fig=None):
if ax is None:
fig, ax = plt.subplots(figsize=(7,6))
# Transform xpos and ypos to figure coordinates by the
# following steps:
# 1. First transform xpos and ypos to data coordinates
# 2. Transform the data coordinates back to figure coordinates
xfig, yfig = ax.transData.transform((xpos, ypos))
trans_to_fig = fig.transFigure.inverted()
xfig, yfig = trans_to_fig.transform((xfig, yfig))
# Calculate figure coordinates from the desired pie chart size
# given in pixels
size = trans_to_fig.transform((size, 0))[0]
# Add axes at data coordinates xpos and ypos. On these axes,
# the pie chart will be plotted
ax_pie = fig.add_axes([xfig-0.5*size, yfig-0.5*size, size, size])
# Plot the pie chart (with some special options)
textprops = {'color' : 'w',
'fontweight' : 'bold',
'fontsize' : 10,
'va' : 'center',
'ha' : 'center'
}
labels = [str(i) if not i == 0 else "" for i in dist]
labeldistance = 0.5
if sum(not x==0 for x in dist) == 1: # Ensures we plot the label in the center
labeldistance = 0.0 # if we have only one entry
ax_pie.pie(dist, labels=labels, labeldistance=labeldistance, textprops=textprops)
return ax_pie
# Read dataset
dataset = pd.read_csv('dataset.txt')
fig, ax = plt.subplots(figsize=(9,5))
# Important, limits must be set before calling draw_pie function!
# (Otherwise, the data coordinates will change, which will break
# the transform sequence inside the draw_pie function!)
ax.set_xlim([-0.2, 2.2]) # Tweak these values for the desired output
ax.set_ylim([0, 6.75])
# Make sure the string from 'Column 1' is displayed again
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(['First Line', 'Second Line', 'Third Line'])
# Remainder of formatting
ax.yaxis.set_major_locator(mticks.MultipleLocator(1))
plt.xticks(fontsize=10)
plt.yticks(fontsize=8)
# Define float values for 'Column 1' (easier for transformation,
# we have already put the text back there using ax.set_xticklabels)
column1_to_float = {'First Line':0, 'Second Line':1, 'Third Line':2}
for (x,y), d in dataset.groupby(['Column 1','Column 2']):
# Only interested in the 'Column 3' column, as this one
# contains the values 1-2-3
d = d['Colour Group Desired']
# Count how often each value (1-2-3) occurs and store
# this in a list (count for value i located at list index
# i-1)
dist = list()
for i in [1,2,3]:
dist.append(d[d==i].count())
# Call your draw_pie function
draw_pie(dist, column1_to_float[x], y, 100, ax=ax, fig=fig)
# Plot the colours (note: using axhspan, they extend the full
# horizontal direction, even while scrolling)
ax.axhspan(0 , 2.25, fc='r' , ec=None, alpha=0.15)
ax.axhspan(2.25, 4.25, fc='orange', ec=None, alpha=0.15)
ax.axhspan(4.25, 6.75, fc='g' , ec=None, alpha=0.15)
# Unfortunately, tight_layout can no longer be used. If we do use this,
# the pie charts will no longer be at the proper positions...
# plt.tight_layout()
plt.show()
If I run this code, I get the following output:
Just to mention it, you can decrease the size of the pie charts by adjusting the size argument to the draw_pie function (I just liked the output above :) ). But keep in mind that in this case, you also want to decrease the fontsize specified in the textprops dictionary in the body of the draw_pie function. As an example (size = 63, fontsize=7):

Plotting classification results in different dates?

I have a data frame (my_data) as follows:
0 2017-01 2017-02 2017-03 2017-04
0 S1 2 3 2 2
1 S2 2 0 2 0
2 S3 1 0 2 2
3 S4 3 2 2 2
4 … … … … …
5 … … … … …
6 S10 2 2 3 2
This data frame is a result of a classification problem in different dates for each sample (S1,.., S10). In order to simplify the plotting I converted the confusion matrix in different numbers as follows: 0 means ‘TP’, 1 means ‘FP’, 2 refers to ‘TN’ and 3 points to ‘FN’. Now, I want to plot this data frame like the below image.
It needs to be mentioned that I already asked this question, but nobody could help me. So, now I tried to make the question more easy to understand that I can get help.
Unfortunately, I don't know of a way to plot one set of data with different markers, so you will have to plot over all your data separately.
You can use matplotlib to plot your data. I'm not sure how your data looks, but for a file with these contents:
2017-01,2017-02,2017-03,2017-04
2,3,2,2
2,0,2,0
1,0,2,2
3,2,2,2
2,2,3,2
You can use the following code to get the plot you want:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
df = pd.read_csv('dataframe.txt', parse_dates = True)
dates = list(df.columns.values) #get dates
number_of_dates = len(dates)
markers = ["o", "d", "^", "s"] #set marker shape
colors = ["g", "r", "m", "y"] #set marker color
# loop over the data in your dataframe
for i in range(df.shape[0]):
# get a row of 1s, 2s, ... as you want your
# data S1, S2, in one line on top of each other
dataY = (i+1)*np.ones(number_of_dates)
# get the data that will specify which marker to use
data = df.loc[i]
# plot dashed line first, setting it underneath markers with zorder
plt.plot(dates, dataY, c="k", linewidth=1, dashes=[6, 2], zorder=1)
# loop over each data point x is the date, y a constant number,
# and data specifies which marker to use
for _x, _y, _data in zip(dates, dataY, data):
plt.scatter(_x, _y, marker=markers[_data], c=colors[_data], s=100, edgecolors="k", linewidths=0.5, zorder=2)
# label your ticks S1, S2, ...
ticklist = list(range(1,df.shape[0]+1))
l2 = [("S%s" % x) for x in ticklist]
ax.set_yticks(ticklist)
ax.set_yticklabels(l2)
labels = ["TP","TN","FP","FN"]
legend_elements = []
for l,c, m in zip(labels, colors, markers):
legend_elements.append(Line2D([0], [0], marker=m, color="w", label=l, markerfacecolor=c, markeredgecolor = "k", markersize=10))
ax.legend(handles=legend_elements, loc='upper right')
plt.show()
Plotting idea from this answer.
This results in a plot looking like this:
EDIT Added dashed line and outline for markers to look more like example in question.
EDIT2 Added legend.

Trying to set y axis labels and ticks aligned to 2D faces

This is my plot:
If I were to draw your attention to the axis labelled 'B' you'll see that everything is not as it should be.
The plots was produced using this:
def newPoly3D(self):
from matplotlib.cm import autumn
# This passes a pandas dataframe of shape (data on rows x 4 columns)
df = self.loadData()
fig = plt.figure(figsize=(10,10))
ax = fig.gca(projection='3d')
vels = [1.42,1.11,0.81,0.50]
which_joints = df.columns
L = len(which_joints)
dmin,dmax = df.min().min(),df.max().max()
dix = df.index.values
offset=-5
for i,j in enumerate(which_joints):
ax.add_collection3d(plt.fill_between(dix,df[j],
dmin,
lw=1.5,
alpha=0.3/float(i+1.),
facecolor=autumn(i/float(L))),
zs=vels[i],
zdir='y')
ax.grid(False)
ax.set_xlabel('A')
ax.set_xlim([0,df.index[-1]])
ax.set_xticks([])
ax.xaxis.set_ticklabels([])
ax.set_axis_off
ax.set_ylabel('B')
ax.set_ylim([0.4, max(vels)+0.075])
ax.set_yticks(vels)
ax.tick_params(direction='out', pad=10)
ax.set_zlabel('C')
ax.set_zlim([dmin,dmax])
ax.xaxis.labelpad = -10
ax.yaxis.labelpad = 15
ax.zaxis.labelpad = 15
# Note the inversion of the axis
plt.gca().invert_yaxis()
First I want to align the ticks on the yaxis (labelled B) with each coloured face. As you can see they are now offset slightly down.
Second I want to align the yaxis tick labels with the above, as you cans see they are currently very much offset downwards. I do not know why.
EDIT:
Here is some example data; each column represents one coloured face on the above plot.
-13.216256 -7.851065 -9.965357 -25.502654
-13.216253 -7.851063 -9.965355 -25.502653
-13.216247 -7.851060 -9.965350 -25.502651
-13.216236 -7.851052 -9.965342 -25.502647
-13.216214 -7.851038 -9.965324 -25.502639
-13.216169 -7.851008 -9.965289 -25.502623
-13.216079 -7.850949 -9.965219 -25.502592
-13.215900 -7.850830 -9.965078 -25.502529
Here we are again, with a simpler plot, reproduced with this data:
k = 10
df = pd.DataFrame(np.array([range(k),
[x + 1 for x in range(k)],
[x + 4 for x in range(k)],
[x + 9 for x in range(k)]]).T,columns=list('abcd'))
If you want to try this with the above function, comment out the df line in the function and change its argument as so def newPoly3D(df): so that you can pass the the test df above.

Plotting results (scatter graph) from DataFrame issues. Python

I am plotting a DataFrame as a scatter graph using this code:
My dataframe somewhat looks like this -
Sector AvgDeg
0 1 52
1 2 52
2 3 52
3 4 54
4 5 52
... ... ...
df.plot.scatter(x='Sector', y='AvgDeg', s=df['AvgDeg'], color='LightBlue',grid=True)
plt.show()
and I'm getting this result:
What I need is to draw every dot with a different color and with the corresponding legend. For example: -blue dot- 'Sector 1', -red dot- 'Sector 2', and so on.
Do you have any idea how to do this? Tks!!
What you have to do is to use a list of the same size as the points in the c parameter of scatter plot.
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
txt = ["text1", "text2", "text3", "text4"]
fig, ax = plt.subplots()
x = np.arange(1, 5)
y = np.arange(1, 5)
#c will change the colors of each point
#s is the size of each point...
#c_map is the color map you want to use
ax.scatter(x, y,s = 40, cmap = cmap_light, c=np.arange(1, 5))
for i, j in enumerate(txt):
#use the below code to display the text for each point
ax.annotate(j, (x[i], y[i]))
plt.show()
What this gives you as a result is -
To assign more different colors for 31 points for example you just gotta change the size...
ax.scatter(x, y,s = 40, cmap = cmap_light, c=np.arange(1, 32))
Similarly you can annotate those points by changing the txt list above.
i would do it this way:
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('ggplot')
colorlist = list(mpl.colors.ColorConverter.colors.keys())
ax = df.plot.scatter(x='Sector', y='AvgDeg', s=df.AvgDeg*1.2,
c=(colorlist * len(df))[:len(df)])
df.apply(lambda x: ax.text(x.Sector, x.AvgDeg, 'Sector {}'.format(x.Sector)), axis=1)
plt.show()
Result

How to label the bars of a stacked bar plot from a pandas DataFrame? [duplicate]

I am trying to replicate the following image in matplotlib and it seems barh is my only option. Though it appears that you can't stack barh graphs so I don't know what to do
If you know of a better python library to draw this kind of thing, please let me know.
This is all I could come up with as a start:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
people = ('A','B','C','D','E','F','G','H')
y_pos = np.arange(len(people))
bottomdata = 3 + 10 * np.random.rand(len(people))
topdata = 3 + 10 * np.random.rand(len(people))
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
ax.barh(y_pos, bottomdata,color='r',align='center')
ax.barh(y_pos, topdata,color='g',align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')
plt.show()
I would then have to add labels individually using ax.text which would be tedious. Ideally I would like to just specify the width of the part to be inserted then it updates the center of that section with a string of my choosing. The labels on the outside (e.g. 3800) I can add myself later, it is mainly the labeling over the bar section itself and creating this stacked method in a nice way I'm having problems with. Can you even specify a 'distance' i.e. span of color in any way?
Edit 2: for more heterogeneous data. (I've left the above method since I find it more usual to work with the same number of records per series)
Answering the two parts of the question:
a) barh returns a container of handles to all the patches that it drew. You can use the coordinates of the patches to aid the text positions.
b) Following these two answers to the question that I noted before (see Horizontal stacked bar chart in Matplotlib), you can stack bar graphs horizontally by setting the 'left' input.
and additionally c) handling data that is less uniform in shape.
Below is one way you could handle data that is less uniform in shape is simply to process each segment independently.
import numpy as np
import matplotlib.pyplot as plt
# some labels for each row
people = ('A','B','C','D','E','F','G','H')
r = len(people)
# how many data points overall (average of 3 per person)
n = r * 3
# which person does each segment belong to?
rows = np.random.randint(0, r, (n,))
# how wide is the segment?
widths = np.random.randint(3,12, n,)
# what label to put on the segment (xrange in py2.7, range for py3)
labels = range(n)
colors ='rgbwmc'
patch_handles = []
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
left = np.zeros(r,)
row_counts = np.zeros(r,)
for (r, w, l) in zip(rows, widths, labels):
print r, w, l
patch_handles.append(ax.barh(r, w, align='center', left=left[r],
color=colors[int(row_counts[r]) % len(colors)]))
left[r] += w
row_counts[r] += 1
# we know there is only one patch but could enumerate if expanded
patch = patch_handles[-1][0]
bl = patch.get_xy()
x = 0.5*patch.get_width() + bl[0]
y = 0.5*patch.get_height() + bl[1]
ax.text(x, y, "%d%%" % (l), ha='center',va='center')
y_pos = np.arange(8)
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')
plt.show()
Which produces a graph like this , with a different number of segments present in each series.
Note that this is not particularly efficient since each segment used an individual call to ax.barh. There may be more efficient methods (e.g. by padding a matrix with zero-width segments or nan values) but this likely to be problem-specific and is a distinct question.
Edit: updated to answer both parts of the question.
import numpy as np
import matplotlib.pyplot as plt
people = ('A','B','C','D','E','F','G','H')
segments = 4
# generate some multi-dimensional data & arbitrary labels
data = 3 + 10* np.random.rand(segments, len(people))
percentages = (np.random.randint(5,20, (len(people), segments)))
y_pos = np.arange(len(people))
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
colors ='rgbwmc'
patch_handles = []
left = np.zeros(len(people)) # left alignment of data starts at zero
for i, d in enumerate(data):
patch_handles.append(ax.barh(y_pos, d,
color=colors[i%len(colors)], align='center',
left=left))
# accumulate the left-hand offsets
left += d
# go through all of the bar segments and annotate
for j in range(len(patch_handles)):
for i, patch in enumerate(patch_handles[j].get_children()):
bl = patch.get_xy()
x = 0.5*patch.get_width() + bl[0]
y = 0.5*patch.get_height() + bl[1]
ax.text(x,y, "%d%%" % (percentages[i,j]), ha='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')
plt.show()
You can achieve a result along these lines (note: the percentages I used have nothing to do with the bar widths, as the relationship in the example seems unclear):
See Horizontal stacked bar chart in Matplotlib for some ideas on stacking horizontal bar plots.
Imports and Test DataFrame
Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2
For vertical stacked bars see Stacked Bar Chart with Centered Labels
import pandas as pd
import numpy as np
# create sample data as shown in the OP
np.random.seed(365)
people = ('A','B','C','D','E','F','G','H')
bottomdata = 3 + 10 * np.random.rand(len(people))
topdata = 3 + 10 * np.random.rand(len(people))
# create the dataframe
df = pd.DataFrame({'Female': bottomdata, 'Male': topdata}, index=people)
# display(df)
Female Male
A 12.41 7.42
B 9.42 4.10
C 9.85 7.38
D 8.89 10.53
E 8.44 5.92
F 6.68 11.86
G 10.67 12.97
H 6.05 7.87
Updated with matplotlib v3.4.2
Use matplotlib.pyplot.bar_label
See How to add value labels on a bar chart for additional details and examples with .bar_label.
labels = [f'{v.get_width():.2f}%' if v.get_width() > 0 else '' for v in c ] for python < 3.8, without the assignment expression (:=).
Plotted using pandas.DataFrame.plot with kind='barh'
ax = df.plot(kind='barh', stacked=True, figsize=(8, 6))
for c in ax.containers:
# customize the label to account for cases when there might not be a bar section
labels = [f'{w:.2f}%' if (w := v.get_width()) > 0 else '' for v in c ]
# set the bar label
ax.bar_label(c, labels=labels, label_type='center')
# uncomment and use the next line if there are no nan or 0 length sections; just use fmt to add a % (the previous two lines of code are not needed, in this case)
# ax.bar_label(c, fmt='%.2f%%', label_type='center')
# move the legend
ax.legend(bbox_to_anchor=(1.025, 1), loc='upper left', borderaxespad=0.)
# add labels
ax.set_ylabel("People", fontsize=18)
ax.set_xlabel("Percent", fontsize=18)
plt.show()
Using seaborn
sns.barplot does not have an option for stacked bar plots, however, sns.histplot and sns.displot can be used to create horizontal stacked bars.
seaborn typically requires the dataframe to be in a long, instead of wide, format, so use pandas.DataFrame.melt to reshape the dataframe.
Reshape dataframe
# convert the dataframe to a long form
df = df.reset_index()
df = df.rename(columns={'index': 'People'})
dfm = df.melt(id_vars='People', var_name='Gender', value_name='Percent')
# display(dfm)
People Gender Percent
0 A Female 12.414557
1 B Female 9.416027
2 C Female 9.846105
3 D Female 8.885621
4 E Female 8.438872
5 F Female 6.680709
6 G Female 10.666258
7 H Female 6.050124
8 A Male 7.420860
9 B Male 4.104433
10 C Male 7.383738
11 D Male 10.526158
12 E Male 5.916262
13 F Male 11.857227
14 G Male 12.966913
15 H Male 7.865684
sns.histplot: axes-level plot
fig, axe = plt.subplots(figsize=(8, 6))
sns.histplot(data=dfm, y='People', hue='Gender', discrete=True, weights='Percent', multiple='stack', ax=axe)
# iterate through each set of containers
for c in axe.containers:
# add bar annotations
axe.bar_label(c, fmt='%.2f%%', label_type='center')
axe.set_xlabel('Percent')
plt.show()
sns.displot: figure-level plot
g = sns.displot(data=dfm, y='People', hue='Gender', discrete=True, weights='Percent', multiple='stack', height=6)
# iterate through each facet / supbplot
for axe in g.axes.flat:
# iteate through each set of containers
for c in axe.containers:
# add the bar annotations
axe.bar_label(c, fmt='%.2f%%', label_type='center')
axe.set_xlabel('Percent')
plt.show()
Original Answer - before matplotlib v3.4.2
The easiest way to plot a horizontal or vertical stacked bar, is to load the data into a pandas.DataFrame
This will plot, and annotate correctly, even when all categories ('People'), don't have all segments (e.g. some value is 0 or NaN)
Once the data is in the dataframe:
It's easier to manipulate and analyze
It can be plotted with the matplotlib engine, using:
pandas.DataFrame.plot.barh
label_text = f'{width}' for annotations
pandas.DataFrame.plot.bar
label_text = f'{height}' for annotations
SO: Vertical Stacked Bar Chart with Centered Labels
These methods return a matplotlib.axes.Axes or a numpy.ndarray of them.
Using the .patches method unpacks a list of matplotlib.patches.Rectangle objects, one for each of the sections of the stacked bar.
Each .Rectangle has methods for extracting the various values that define the rectangle.
Each .Rectangle is in order from left the right, and bottom to top, so all the .Rectangle objects, for each level, appear in order, when iterating through .patches.
The labels are made using an f-string, label_text = f'{width:.2f}%', so any additional text can be added as needed.
Plot and Annotate
Plotting the bar, is 1 line, the remainder is annotating the rectangles
# plot the dataframe with 1 line
ax = df.plot.barh(stacked=True, figsize=(8, 6))
# .patches is everything inside of the chart
for rect in ax.patches:
# Find where everything is located
height = rect.get_height()
width = rect.get_width()
x = rect.get_x()
y = rect.get_y()
# The height of the bar is the data value and can be used as the label
label_text = f'{width:.2f}%' # f'{width:.2f}' to format decimal values
# ax.text(x, y, text)
label_x = x + width / 2
label_y = y + height / 2
# only plot labels greater than given width
if width > 0:
ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
# move the legend
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
# add labels
ax.set_ylabel("People", fontsize=18)
ax.set_xlabel("Percent", fontsize=18)
plt.show()
Example with Missing Segment
# set one of the dataframe values to 0
df.iloc[4, 1] = 0
Note the annotations are all in the correct location from df.
For this case, the above answers work perfectly. The issue I had, and didn't find a plug-and-play solution online, was that I often have to plot stacked bars in multi-subplot figures, with many values, which tend to have very non-homogenous amplitudes.
(Note: I work usually with pandas dataframes, and matplotlib. I couldn't make the bar_label() method of matplotlib to work all the times.)
So, I just give a kind of ad-hoc, but easily generalizable solution. In this example, I was working with single-row dataframes (for power-exchange monitoring purposes per hour), so, my dataframe (df) had just one row.
(I provide an example figure to show how this can be useful in very densely-packed plots)
[enter image description here][1]
[1]: https://i.stack.imgur.com/9akd8.png
'''
This implementation produces a stacked, horizontal bar plot.
df --> pandas dataframe. Columns are used as the iterator, and only the firs value of each column is used.
waterfall--> bool: if True, apart from the stack-direction, also a perpendicular offset is added.
cyclic_offset_x --> list (of any length) or None: loop through these values to use as x-offset pixels.
cyclic_offset_y --> list (of any length) or None: loop through these values to use as y-offset pixels.
ax --> matplotlib Axes, or None: if None, creates a new axis and figure.
'''
def magic_stacked_bar(df, waterfall=False, cyclic_offset_x=None, cyclic_offset_y=None, ax=None):
if isinstance(cyclic_offset_x, type(None)):
cyclic_offset_x = [0, 0]
if isinstance(cyclic_offset_y, type(None)):
cyclic_offset_y = [0, 0]
ax0 = ax
if isinstance(ax, type(None)):
fig, ax = plt.subplots()
fig.set_size_inches(19, 10)
cycler = 0;
prev = 0 # summation variable to make it stacked
for c in df.columns:
if waterfall:
y = c ; label = "" # bidirectional stack
else:
y = 0; label = c # unidirectional stack
ax.barh(y=y, width=df[c].values[0], height=1, left=prev, label = label)
prev += df[c].values[0] # add to sum-stack
offset_x = cyclic_offset_x[divmod(cycler, len(cyclic_offset_x))[1]]
offset_y = cyclic_offset_y[divmod(cycler, len(cyclic_offset_y))[1]]
ax.annotate(text="{}".format(int(df[c].values[0])), xy=(prev - df[c].values / 2, y),
xytext=(offset_x, offset_y), textcoords='offset pixels',
ha='center', va='top', fontsize=8,
arrowprops=dict(facecolor='black', shrink=0.01, width=0.3, headwidth=0.3),
bbox=dict(boxstyle='round', facecolor='grey', alpha=0.5))
cycler += 1
if not waterfall:
ax.legend() # if waterfall, the index annotates the columns. If
# waterfall ==False, the legend annotates the columns
if isinstance(ax0, type(None)):
ax.set_title("Voi la")
ax.set_xlabel("UltraWatts")
plt.show()
else:
return ax
''' (Sometimes, it is more tedious and requires some custom functions to make the labels look alright.
'''
A, B = 80,80
n_units = df.shape[1]
cyclic_offset_x = -A*np.cos(2*np.pi / (2*n_units) *np.arange(n_units))
cyclic_offset_y = B*np.sin(2*np.pi / (2*n_units) * np.arange(n_units)) + B/2

Categories