This question already has answers here:
How to plot and annotate grouped bars in seaborn / matplotlib
(1 answer)
How to add value labels on a bar chart
(7 answers)
Closed 1 year ago.
I want to show my values in hbar diagram but somehow I'm not able to render the values right to the bars.
Here is my code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
index = ['average', '50th', '95th', '99.9th', 'max']
aaa = [3180, 2153, 9172, 9368, 9432]
bbb = [3857, 3367, 11638, 14555, 14731]
ccc = [740, 716, 1326, 1927, 2591]
df = pd.DataFrame({'aaa': aaa, 'bbb': bbb, 'ccc': ccc}, index=index)
ax = df.plot.barh()
How can I display my values to each bar and is also possible to save the figure for e.g. .png file?
Related
This question already has answers here:
Create a grouped bar plot using seaborn
(2 answers)
Plot bar chart in multiple subplot rows with Pandas
(1 answer)
Plotting a bar chart with seaborn
(1 answer)
Seaborn Catplot set values over the bars
(3 answers)
How to make multiple plots with seaborn from a wide dataframe
(2 answers)
Closed 8 months ago.
I would like to create a subplot of bar chart where '% of total' is the y-axis and 'plants' is the x-axis. Also 'brand' will be legend, so in this case 3 different charts for the 3 different 'brands'. Each groups % adds up to 100%. I started with the code below, but got stuck. Please see a sample of the data below and image below;
import pandas as pd
import numpy as np
df = pd.DataFrame({
'brand':['A','A', 'A', 'B','B', 'B' ,'C','C', 'C'],
'plants':[0, 1, 2, 0,1,2,0,1,2],
'% of total':[80, 12, 8, 67, 18, 5,35, 40,25],
})
plt.figure(figsize=(10, 10))
for i, brand in enumerate(['A', 'B', 'C']):
You can use seaborn and catplot:
# Python env: pip install seaborn
# Anaconda env: conda install seaborn
import seaborn as sns
import matplotlib.pyplot as plt
sns.catplot(x='plants', y='% of total', col='brand', data=df, kind='bar')
plt.show()
Output:
Does this need to be in a for loop? You could simply grab the relevant rows using pandas.
For example:
my_A_df = df[df['brand'] == A]
plt.hist(my_A_df)
plt.bar(my_A_df['plants'], my_A_df['% of total'])
This will work for generating a barplot for each. Not sure if this is within the bounds of your problem but happy to edit if necessary.
This question already has an answer here:
Using pandas value_counts and matplotlib
(1 answer)
Closed 8 months ago.
I have a dataframe with several columns and I need to plot a graph based on the number of counts in the 'Total'column.
I performed the following code:
df['Total'].value_counts()
The output are as follows:
2 10
20 15
4 8
8 20
This means the the number 2 appears in the Total columns 10 times, number 20 appears 15 times and so on.
How do I plot a barchart with the x-axis as the number itself and the y-axis as the occurances and in ascending
order? The x-axis will plot 2 -> 4 -> 8 -> 20.
What are the next steps after:
%matplotlib inline
import matplotlib.pyplot as plt
Consider this as an example:
This denoted your 'Total' column -> [2,2,2,2,2,20,20,20,20,4,4,4,8,8,8,8,8]
import pandas as pd
import matplotlib.pyplot as plt
import collections
total = [2,2,2,2,2,20,20,20,20,4,4,4,8,8,8,8,8]
df = pd.DataFrame(total, columns=['total'])
#print(df.value_counts())
fig,ax = plt.subplots()
df['total'].value_counts().plot(ax = ax, kind = 'bar', ylabel = 'frequency')
plt.show()
This gives the following output:
This question already has answers here:
Format y axis as percent
(10 answers)
Closed 2 years ago.
I am just wondering, how do I add a percentage (%) symbol after each value in my plot along the X axis, not converting the values to a percentage?
For example: Say I have the values 5, 10, 15, 20... How would I make them appear as 5%, 10%, 15%, 20% etc., along the X axis, but not converting them to 0.05%, 0.1%, 0.15%, 0.2% etc.
Code for my plot:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(
What needs to be added to my plot code to make the percentage (%) symbol appear after each value in my X axis?
sns.displot(data=df, x="column_name", kde=True)
PercentFormatter() should work for you as shown in the working example below:
import seaborn as sns
import numpy as np
import matplotlib.ticker as mtick
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.randn(100)
fig, ax = plt.subplots(figsize=(16,8))
sns.distplot(x, vertical=True)
Then, at the end do:
ax.xaxis.set_major_formatter(mtick.PercentFormatter())
I am trying to create a stacked barplot using a data frame I have created that
looks like this
I want the stacked bar chart to show the 'types of exploitation' on the x axis, and then the male and female figures stacked on top of each other under these headings.
Is there a way to do this reading the info from my df? I have read about creating an index to do this but do not understand if this is the solution?
I also need a legend showing 'male' and 'female'
You can stack bars on top of eachother by the bottom function in matplotlib package.
Step 1: Create dataframe and import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
d = {'male': [37,1032,1], 'female': [96,134,1]}
df = pd.DataFrame(data=d, index=['a', 'b', 'c'])
Step 2: Create graph
r = [0,1,2]
bars1 = df['female']
bars2 = df['male']
plt.bar(r, bars1)
plt.bar(r, bars2,bottom=bars1, color='#557f2d')
plt.xticks(r, df.index, fontweight='bold')
plt.legend(labels = ['female', 'male'])
plt.show()
More information could be found on this webpage: Link
This question already has answers here:
Pandas Dataframe line plot display date on xaxis
(1 answer)
How to get ticks every hour
(2 answers)
datetime dtypes in pandas read_csv
(6 answers)
Closed 4 years ago.
I am trying to plot time series data, and label the x-axis by month.
This is the first few of my dataframe:
Time Value
2012-01-01 00:00:00 1.223
2012-01-01 00:00:30 2.132
2012-01-01 00:01:00 1.417
2012-01-01 00:01:30 1.767
And my code is as follows:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator
%matplotlib inline
df = pd.read_csv('data.csv', index_col=0)
value = df.value
plt.figure(figsize=(15,10))
ax = value.plot(x_compat=True)
ax.xaxis.set_major_locator(MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.NullFormatter())
plt.show()
As suggested in other answers, I already added the (x_compat=True) argument. However, this doesn't give the ticks and ticklabels of my x-axis at all. How can I fix this?
And I also tried the second way with matplotlib by this
plt.figure(figsize=(15,10))
plt.plot(df.index, df.value)
plt.gca().xaxis.set_major_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(DateFormatter("%M"))
But still I can't see the ticklabels in month. It doesn't give me anything on x-axis.
Answer I should convert df.index using to_datatime first.