Consider my series as below: First column is article_id and the second column is frequency count.
article_id 1 39 2 49 3 187 4 159 5 158 ... 16947 14 16948 7 16976 2 16977 1 16978 1 16980 1 Name: article_id, dtype: int64
I got this series from a dataframe with the following command:
logs.loc[logs['article_id'] <= 17029].groupby('article_id')['article_id'].count()
logs is the dataframe here and article_id is one of the columns in it.
How do I plot a bar chart(using Matlplotlib) such that the article_id is on the X-axis and the frequency count on the Y-axis ?
My natural instinct was to convert it into a list using .tolist() but that doesn't preserve the article_id.
Series instance, plots a vertical bar chart. In the same way, to plot a bar chart for a DataFrame, the bar() function can be invoked on the plot member of a pandas DataFrame instance. A horizontal bar chart for the series data can be plotted using the barh() function of Series. plot member.
Traditionally, bar plots use the y-axis to show how values compare to each other. In order to make a bar plot from your DataFrame, you need to pass a X-value and a Y-value. Pandas will draw a chart for you automatically. Pseudo Code: Construct a bar plot from a column(s) and index within a DataFrame.
IIUC you need Series.plot.bar
:
#pandas 0.17.0 and above s.plot.bar() #pandas below 0.17.0 s.plot('bar')
Sample:
import pandas as pd import matplotlib.pyplot as plt s = pd.Series({16976: 2, 1: 39, 2: 49, 3: 187, 4: 159, 5: 158, 16947: 14, 16977: 1, 16948: 7, 16978: 1, 16980: 1}, name='article_id') print (s) 1 39 2 49 3 187 4 159 5 158 16947 14 16948 7 16976 2 16977 1 16978 1 16980 1 Name: article_id, dtype: int64 s.plot.bar() plt.show()
The new pandas API suggests the following way:
import pandas as pd s = pd.Series({16976: 2, 1: 39, 2: 49, 3: 187, 4: 159, 5: 158, 16947: 14, 16977: 1, 16948: 7, 16978: 1, 16980: 1}, name='article_id') s.plot(kind="bar", figsize=(20,10))
If you are working on Jupyter, you don't need the matplotlib
library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With