1

I have a pandas dataframe in Python that looks like this:

  Jan 15   Feb 15   March 15   April 15
1   val      val      val       val
2   val      val      val       val 
3   val      val      val       nan
4   val      nan      val       nan
5   val      nan      nan       nan

I want to plot a graph as follows. The X axis is the months (Jan 15 | Feb 15 | March 15 | April 15), and the bars are like so:

Jan 15: 5
Feb 15: 3
March 15: 4
April 15: 2

^ this is the count of non-null values for each month.

Any help on how to plot it with matplotlib or anything else?

EDIT: the values in the df are tuples like so: (val1, val2).

2 Answers 2

2

You need count with Series.plot.bar:

import matplotlib.pyplot as plt
df.count().plot.bar()
plt.show()

Solution with Series.plot:

import matplotlib.pyplot as plt
df.count().plot(kind='bar')
plt.show()

graph

Sign up to request clarification or add additional context in comments.

2 Comments

is there a wat to make a tag cloud of it? for example, instead of a graph, plot in a tag cloud the months, and the largest font moth would be the one with the most data?
Hmmm, in pandas it is not possible, I am not sure if in matplotlib. I found this solution, try it.
2

This will return a series with the data you want to plot:

df.count()

This will plot it:

df.count().plot.bar();  # the semicolon will suppress output in Jupyter

Edit: made it a bar chart.

7 Comments

how do I plot the graph? it prints: <matplotlib.axes._subplots.AxesSubplot at 0x20e3fbc8ef0>
I assume you're in Jupyter. You have to enable inline charts by running %matplotlib inline once.
import matplotlib.pyplot as plt. Then after df.count().plot(), add plt.show(). If you're using jupyter notebook you can also use the magic %matplotlib inline. @IanS: add kind='bar' in your plot call
df.count().plot(kind='bar', stacked=True) is an alternative syntax. The stacked argument is worth knowing about too.
As far as I know, literally anywhere else than jupyter notebook with matplotlib inline. I made a habit of always including it. It also mutes down the classic output of a collection of axes when you plot without capturing the axes
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.