How to show percentage (text) next to the horizontal bars in matplotlib? The Next CEO of Stack Overflow2019 Community Moderator ElectionPython Seaborn: how are error bars computed in barplots?How to plot a contour map in python using matplotlib?how to plot a matplotlib non blocking figure using mpl_connect?How to plot a 3-axis bar chart with matplotlib (and pandas + jupyter)How to create a historical timeline using Pandas Dataframe and matplotlibHow to extract numerical data from a matplotlib scatter plot in python?What is the concept of error bars in barplots in seaborn library?tsne plot not showing all the labels?seaborn regplot does not show the line

Reshaping json / reparing json inside shell script (remove trailing comma)

Redefining symbol midway through a document

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Are the names of these months realistic?

TikZ: How to fill area with a special pattern?

What happened in Rome, when the western empire "fell"?

Is it convenient to ask the journal's editor for two additional days to complete a review?

What difference does it make using sed with/without whitespaces?

Won the lottery - how do I keep the money?

Decide between Polyglossia and Babel for LuaLaTeX in 2019

Purpose of level-shifter with same in and out voltages

Is there a reasonable and studied concept of reduction between regular languages?

Players Circumventing the limitations of Wish

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Can someone explain this formula for calculating Manhattan distance?

Which one is the true statement?

How to avoid supervisors with prejudiced views?

Can Sneak Attack be used when hitting with an improvised weapon?

Easy to read palindrome checker

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

(How) Could a medieval fantasy world survive a magic-induced "nuclear winter"?

Why is information "lost" when it got into a black hole?

Is it ok to trim down a tube patch?

Pulling the principal components out of a DimensionReducerFunction?



How to show percentage (text) next to the horizontal bars in matplotlib?



The Next CEO of Stack Overflow
2019 Community Moderator ElectionPython Seaborn: how are error bars computed in barplots?How to plot a contour map in python using matplotlib?how to plot a matplotlib non blocking figure using mpl_connect?How to plot a 3-axis bar chart with matplotlib (and pandas + jupyter)How to create a historical timeline using Pandas Dataframe and matplotlibHow to extract numerical data from a matplotlib scatter plot in python?What is the concept of error bars in barplots in seaborn library?tsne plot not showing all the labels?seaborn regplot does not show the line










1












$begingroup$


I am using seaborn's countplot to show count distribution of 2 categorical data. Fine it works but I want the percentages to show on top of the bars for each of the plot. Please how do I do it?



fig, ax = plt.subplots(1, 2)
sns.countplot(y = df['current_status'], ax=ax[0]).set_title('Current Occupation')
sns.countplot(df['gender'], ax=ax[1]).set_title('Gender distribution')


enter image description here



I have made edits based on the comments made but I can't get the percentages to the right of horizontal bars. This is what I have done.



total = len(df['current_status'])*1.
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

for p in ax.patches:
ax.annotate(':.1f%'.format(100*p.get_height()/total), (p.get_y()+0.1, p.get_height()+5))
_ = ax.set_xticklabels(map(':.1f%'.format, 100*ax.xaxis.get_majorticklocs()/total))


enter image description here










share|improve this question









New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 1




    $begingroup$
    stackoverflow.com/questions/33179122/…
    $endgroup$
    – Alexis
    Mar 26 at 15:00










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    Mar 26 at 15:58










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    Mar 26 at 16:06















1












$begingroup$


I am using seaborn's countplot to show count distribution of 2 categorical data. Fine it works but I want the percentages to show on top of the bars for each of the plot. Please how do I do it?



fig, ax = plt.subplots(1, 2)
sns.countplot(y = df['current_status'], ax=ax[0]).set_title('Current Occupation')
sns.countplot(df['gender'], ax=ax[1]).set_title('Gender distribution')


enter image description here



I have made edits based on the comments made but I can't get the percentages to the right of horizontal bars. This is what I have done.



total = len(df['current_status'])*1.
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

for p in ax.patches:
ax.annotate(':.1f%'.format(100*p.get_height()/total), (p.get_y()+0.1, p.get_height()+5))
_ = ax.set_xticklabels(map(':.1f%'.format, 100*ax.xaxis.get_majorticklocs()/total))


enter image description here










share|improve this question









New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 1




    $begingroup$
    stackoverflow.com/questions/33179122/…
    $endgroup$
    – Alexis
    Mar 26 at 15:00










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    Mar 26 at 15:58










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    Mar 26 at 16:06













1












1








1





$begingroup$


I am using seaborn's countplot to show count distribution of 2 categorical data. Fine it works but I want the percentages to show on top of the bars for each of the plot. Please how do I do it?



fig, ax = plt.subplots(1, 2)
sns.countplot(y = df['current_status'], ax=ax[0]).set_title('Current Occupation')
sns.countplot(df['gender'], ax=ax[1]).set_title('Gender distribution')


enter image description here



I have made edits based on the comments made but I can't get the percentages to the right of horizontal bars. This is what I have done.



total = len(df['current_status'])*1.
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

for p in ax.patches:
ax.annotate(':.1f%'.format(100*p.get_height()/total), (p.get_y()+0.1, p.get_height()+5))
_ = ax.set_xticklabels(map(':.1f%'.format, 100*ax.xaxis.get_majorticklocs()/total))


enter image description here










share|improve this question









New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I am using seaborn's countplot to show count distribution of 2 categorical data. Fine it works but I want the percentages to show on top of the bars for each of the plot. Please how do I do it?



fig, ax = plt.subplots(1, 2)
sns.countplot(y = df['current_status'], ax=ax[0]).set_title('Current Occupation')
sns.countplot(df['gender'], ax=ax[1]).set_title('Gender distribution')


enter image description here



I have made edits based on the comments made but I can't get the percentages to the right of horizontal bars. This is what I have done.



total = len(df['current_status'])*1.
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

for p in ax.patches:
ax.annotate(':.1f%'.format(100*p.get_height()/total), (p.get_y()+0.1, p.get_height()+5))
_ = ax.set_xticklabels(map(':.1f%'.format, 100*ax.xaxis.get_majorticklocs()/total))


enter image description here







python matplotlib seaborn






share|improve this question









New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Mar 26 at 21:09









Esmailian

2,272218




2,272218






New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Mar 26 at 14:57









radioactiveradioactive

1084




1084




New contributor




radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






radioactive is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1




    $begingroup$
    stackoverflow.com/questions/33179122/…
    $endgroup$
    – Alexis
    Mar 26 at 15:00










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    Mar 26 at 15:58










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    Mar 26 at 16:06












  • 1




    $begingroup$
    stackoverflow.com/questions/33179122/…
    $endgroup$
    – Alexis
    Mar 26 at 15:00










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    Mar 26 at 15:55










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    Mar 26 at 15:58










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    Mar 26 at 16:06







1




1




$begingroup$
stackoverflow.com/questions/33179122/…
$endgroup$
– Alexis
Mar 26 at 15:00




$begingroup$
stackoverflow.com/questions/33179122/…
$endgroup$
– Alexis
Mar 26 at 15:00












$begingroup$
@Alexis, please I have made edits to the question.
$endgroup$
– radioactive
Mar 26 at 15:55




$begingroup$
@Alexis, please I have made edits to the question.
$endgroup$
– radioactive
Mar 26 at 15:55












$begingroup$
@Esmailian I have made some edits but I still have some issues. Please take a look.
$endgroup$
– radioactive
Mar 26 at 15:55




$begingroup$
@Esmailian I have made some edits but I still have some issues. Please take a look.
$endgroup$
– radioactive
Mar 26 at 15:55












$begingroup$
It is better to say "I want the percentages to the right of horizontal bars"
$endgroup$
– Esmailian
Mar 26 at 15:58




$begingroup$
It is better to say "I want the percentages to the right of horizontal bars"
$endgroup$
– Esmailian
Mar 26 at 15:58












$begingroup$
@Esmailian I have edited it Sir. So whats the solution?
$endgroup$
– radioactive
Mar 26 at 16:06




$begingroup$
@Esmailian I have edited it Sir. So whats the solution?
$endgroup$
– radioactive
Mar 26 at 16:06










1 Answer
1






active

oldest

votes


















1












$begingroup$

Here is a working example to add a text to the right of horizontal bars:



import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.array([['a'], ['a'], ['b']]), columns=['current_status'])
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

total = len(df['current_status'])
for p in ax.patches:
percentage = ':.1f%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
ax.annotate(percentage, (x, y))

plt.show()


Output:





You can move the texts around by changing the formula for x and y. For example, to place them on top:



x = p.get_x() + p.get_width() / 2
y = p.get_y() - 0.02


Here is a general guideline for annotating axes.






share|improve this answer











$endgroup$












  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    Mar 26 at 17:24











Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
);
);
, "mathjax-editing");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "557"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






radioactive is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f48035%2fhow-to-show-percentage-text-next-to-the-horizontal-bars-in-matplotlib%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1












$begingroup$

Here is a working example to add a text to the right of horizontal bars:



import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.array([['a'], ['a'], ['b']]), columns=['current_status'])
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

total = len(df['current_status'])
for p in ax.patches:
percentage = ':.1f%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
ax.annotate(percentage, (x, y))

plt.show()


Output:





You can move the texts around by changing the formula for x and y. For example, to place them on top:



x = p.get_x() + p.get_width() / 2
y = p.get_y() - 0.02


Here is a general guideline for annotating axes.






share|improve this answer











$endgroup$












  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    Mar 26 at 17:24















1












$begingroup$

Here is a working example to add a text to the right of horizontal bars:



import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.array([['a'], ['a'], ['b']]), columns=['current_status'])
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

total = len(df['current_status'])
for p in ax.patches:
percentage = ':.1f%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
ax.annotate(percentage, (x, y))

plt.show()


Output:





You can move the texts around by changing the formula for x and y. For example, to place them on top:



x = p.get_x() + p.get_width() / 2
y = p.get_y() - 0.02


Here is a general guideline for annotating axes.






share|improve this answer











$endgroup$












  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    Mar 26 at 17:24













1












1








1





$begingroup$

Here is a working example to add a text to the right of horizontal bars:



import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.array([['a'], ['a'], ['b']]), columns=['current_status'])
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

total = len(df['current_status'])
for p in ax.patches:
percentage = ':.1f%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
ax.annotate(percentage, (x, y))

plt.show()


Output:





You can move the texts around by changing the formula for x and y. For example, to place them on top:



x = p.get_x() + p.get_width() / 2
y = p.get_y() - 0.02


Here is a general guideline for annotating axes.






share|improve this answer











$endgroup$



Here is a working example to add a text to the right of horizontal bars:



import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.array([['a'], ['a'], ['b']]), columns=['current_status'])
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of Configurations')
plt.xlabel('Number of Axles')

total = len(df['current_status'])
for p in ax.patches:
percentage = ':.1f%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
ax.annotate(percentage, (x, y))

plt.show()


Output:





You can move the texts around by changing the formula for x and y. For example, to place them on top:



x = p.get_x() + p.get_width() / 2
y = p.get_y() - 0.02


Here is a general guideline for annotating axes.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 26 at 16:46

























answered Mar 26 at 16:37









EsmailianEsmailian

2,272218




2,272218











  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    Mar 26 at 17:24
















  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    Mar 26 at 17:24















$begingroup$
Thank you for your assistance.
$endgroup$
– radioactive
Mar 26 at 17:24




$begingroup$
Thank you for your assistance.
$endgroup$
– radioactive
Mar 26 at 17:24










radioactive is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















radioactive is a new contributor. Be nice, and check out our Code of Conduct.












radioactive is a new contributor. Be nice, and check out our Code of Conduct.











radioactive is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Data Science Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f48035%2fhow-to-show-percentage-text-next-to-the-horizontal-bars-in-matplotlib%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

Luettelo Yhdysvaltain laivaston lentotukialuksista Lähteet | Navigointivalikko

Gary (muusikko) Sisällysluettelo Historia | Rockin' High | Lähteet | Aiheesta muualla | NavigointivalikkoInfobox OKTuomas "Gary" Keskinen Ancaran kitaristiksiProjekti Rockin' High