0

I am trying to graph multi indexing plot using matplotlib. However, I was struggling to find the exact code from the previously answered code. Can anyone assist me how can I produce similar graph.

enter image description here

import pandas as pd
import matplotlib.pyplot as plt
import pylab as pl 
import numpy as np
import pandas 

xls_filename = "abc.xlsx"
f = pandas.ExcelFile(xls_filename)
df = f.parse("Sheet1", index_col='Year' and 'Month')
f.close()

matplotlib.rcParams.update({'font.size': 18})  # Font size of x and y-axis
df.plot(kind= 'bar', alpha=0.70)

It is not indexing as I wanted and not produced the graph as expected as well. Help appreciated.

1 Answer 1

1

I created a DataFrame from some of the values I see on your attached plot and plotted it.

index = pd.MultiIndex.from_tuples(tuples=[(2011, ), (2012, ), (2016, 'M'), (2016, 'J')], names=['year', 'month'])
df = pd.DataFrame(index=index, data={'1': [10, 140, 6, 9], '2': [23, 31, 4, 5], '3': [33, 23, 1, 1]})
df.plot(kind='bar')

This is the outcome

enter image description here

where the DataFrame is this

enter image description here

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

3 Comments

Hi @Uğur Güney, thanks. Any idea how to eliminate the NaN from the graph. I tried df[~np.isnan(df)] where df is the current dataframe.
Hi! np.isnan(df) or df.isnan() checks only the values of a dataframe, not its indices. And if you look at the month level index via df.index.levels[1] you see that there are no None's in there. I guess those NaNs appear only when the df table is displayed. I put single quotes to month section instead of leaving it empty when creating the tuples: tuples=[(2011, ''), (2012, ''), (2016, 'M'), (2016, 'J')] Still not a nice solution but at least you don't see the word "NaN" on the plot.
hmm...Thats interesting. I did try the similar to avoid NaN, however still the bracket appear on the graph. But, your method gave an idea to produce a graph like the above.

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.