How to show percentage (text) next to the horizontal bars in matplotlib?2019 Community Moderator ElectionCreate continous plot using matplotlib/seaborn with specific huehow to plot a matplotlib non blocking figure using mpl_connect?How to create a historical timeline using Pandas Dataframe and matplotlibHow to extract numerical data from a matplotlib scatter plot in python?Matplotlib — TypeError: 'module' object is not callableggplot (in R)/matplotlib (in Python) with linear model?What is the concept of error bars in barplots in seaborn library?seaborn regplot does not show the lineHow to set limits of Y-axes in countplot?How to use Matplotlib FixedLocator ticker locs parameter

Your magic is very sketchy

Go Pregnant or Go Home

voltage of sounds of mp3files

The baby cries all morning

How does residential electricity work?

Cynical novel that describes an America ruled by the media, arms manufacturers, and ethnic figureheads

How do I define a right arrow with bar in LaTeX?

At which point does a character regain all their Hit Dice?

Why are all the doors on Ferenginar (the Ferengi home world) far shorter than the average Ferengi?

Why did Kant, Hegel, and Adorno leave some words and phrases in the Greek alphabet?

Applicability of Single Responsibility Principle

What to do with wrong results in talks?

Mapping a list into a phase plot

Time travel short story where a man arrives in the late 19th century in a time machine and then sends the machine back into the past

What's a natural way to say that someone works somewhere (for a job)?

How do I keep an essay about "feeling flat" from feeling flat?

How to prove that the query oracle is unitary?

What is the oldest known work of fiction?

Can I Retrieve Email Addresses from BCC?

Greatest common substring

I'm in charge of equipment buying but no one's ever happy with what I choose. How to fix this?

The plural of 'stomach"

Why Were Madagascar and New Zealand Discovered So Late?

Best way to store options for panels



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



2019 Community Moderator ElectionCreate continous plot using matplotlib/seaborn with specific huehow to plot a matplotlib non blocking figure using mpl_connect?How to create a historical timeline using Pandas Dataframe and matplotlibHow to extract numerical data from a matplotlib scatter plot in python?Matplotlib — TypeError: 'module' object is not callableggplot (in R)/matplotlib (in Python) with linear model?What is the concept of error bars in barplots in seaborn library?seaborn regplot does not show the lineHow to set limits of Y-axes in countplot?How to use Matplotlib FixedLocator ticker locs parameter










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
    6 hours ago










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    5 hours ago










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    5 hours ago















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
    6 hours ago










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    5 hours ago










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    5 hours ago













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 32 mins ago









Esmailian

1,881116




1,881116






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 6 hours ago









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
    6 hours ago










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    5 hours ago










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    5 hours ago












  • 1




    $begingroup$
    stackoverflow.com/questions/33179122/…
    $endgroup$
    – Alexis
    6 hours ago










  • $begingroup$
    @Alexis, please I have made edits to the question.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    @Esmailian I have made some edits but I still have some issues. Please take a look.
    $endgroup$
    – radioactive
    5 hours ago










  • $begingroup$
    It is better to say "I want the percentages to the right of horizontal bars"
    $endgroup$
    – Esmailian
    5 hours ago










  • $begingroup$
    @Esmailian I have edited it Sir. So whats the solution?
    $endgroup$
    – radioactive
    5 hours ago







1




1




$begingroup$
stackoverflow.com/questions/33179122/…
$endgroup$
– Alexis
6 hours ago




$begingroup$
stackoverflow.com/questions/33179122/…
$endgroup$
– Alexis
6 hours ago












$begingroup$
@Alexis, please I have made edits to the question.
$endgroup$
– radioactive
5 hours ago




$begingroup$
@Alexis, please I have made edits to the question.
$endgroup$
– radioactive
5 hours ago












$begingroup$
@Esmailian I have made some edits but I still have some issues. Please take a look.
$endgroup$
– radioactive
5 hours ago




$begingroup$
@Esmailian I have made some edits but I still have some issues. Please take a look.
$endgroup$
– radioactive
5 hours ago












$begingroup$
It is better to say "I want the percentages to the right of horizontal bars"
$endgroup$
– Esmailian
5 hours ago




$begingroup$
It is better to say "I want the percentages to the right of horizontal bars"
$endgroup$
– Esmailian
5 hours ago












$begingroup$
@Esmailian I have edited it Sir. So whats the solution?
$endgroup$
– radioactive
5 hours ago




$begingroup$
@Esmailian I have edited it Sir. So whats the solution?
$endgroup$
– radioactive
5 hours ago










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
    4 hours ago










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
    4 hours ago















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
    4 hours ago













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 4 hours ago

























answered 5 hours ago









EsmailianEsmailian

1,881116




1,881116











  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    4 hours ago
















  • $begingroup$
    Thank you for your assistance.
    $endgroup$
    – radioactive
    4 hours ago















$begingroup$
Thank you for your assistance.
$endgroup$
– radioactive
4 hours ago




$begingroup$
Thank you for your assistance.
$endgroup$
– radioactive
4 hours ago










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