Transposing x and y axes with matplotlib and pandas

Question:

I’m trying to use a bar chart to visualize my csv data. The data looks like this:

question,count_1,count_2,count_3,count_4,count_5
Q1,0,0,6,0,0
Q2,6,0,0,0,0
Q3,3,2,1,0,0
Q4,0,0,6,0,0
Q5,6,0,0,0,0
Q6,0,6,0,0,0
Q7,6,0,0,0,0
Q8,0,0,0,5,1
Q9,1,4,0,0,1
Q10,0,0,1,5,0

Here is my code

import pandas as pd
import csv
import matplotlib.pyplot as plt

df = pd.read_csv('example.csv')
ax = df.set_index(['question']).plot.bar(stacked=True)
ax.legend(loc='best')
plt.show()

Which gives me:

plot

What I’m trying to do is flip the x and y axes. I want the bars to be horizontal and y axis to be the questions. I tried to transpose my data frame using:

ax = df.set_index(['question']).T.plot.bar(stacked=True)

but that gives me:

plot_2

which is not what I want. Can anyone help?

Asked By: Monika

||

Answers:

to get the bars horizontally (flip the x and y axis), you need to use barh (horizontal bar). More info here. So, the code would be…

import pandas as pd
import csv
import matplotlib.pyplot as plt

df = pd.read_csv('example.csv')
ax = df.set_index(['question']).plot.barh(stacked=True)
ax.legend(loc='best')
plt.show()

Output plot

enter image description here

Answered By: Redox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.