0

I want to create a horizontal bar chart, however I think I would have to use the pivot method first. The current dataframe consists of two rows and many columns:

    Names       not_needed     not_needed2         year1         year2         year3
    Joe         0              0                   240.87        2.30          0.85
    Doe         0              0                   243.72        2.35          0.84

To plot this into a bar chart I would like to first transform the data into this:

    Years       Joe        Doe   
    year1       240.87     243.72    
    year2       2.30       2.35  
    year3       .85        .84 

This way I can have two horizontal bar charts stacked on top of each other where the y axis labels the years and the x axis labels the data numbers.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
HoopsMcCann
  • 347
  • 2
  • 3
  • 18

2 Answers2

0

I changed a bit the values so the bars show.

You can do something like that

import pandas as pd
import matplotlib.pyplot as plt

columns = ['Names', 'year1', 'year2', 'year3']
df = pd.read_csv('data.csv', usecols=columns)
transpose_df = df.set_index('Names').transpose()
# If names are not unique, you might want to group by and aggregate
# transpose_df = df.groupby('Names').mean().transpose()
print(transpose_df)
transpose_df.plot.barh()
plt.show()

Which prints

Names     Joe     Doe
year1  240.87  243.72
year2   60.00   20.00
year3  100.00  150.00

And produces

HBar

CSV I used

Names,not_needed,not_needed2,year1,year2,year3
Joe,0,0,240.87,60,100
Doe,0,0,243.72,20,150
tchar
  • 838
  • 9
  • 12
0

Just a simple transpose will do actually. No need for a pivot.

df1 = df.set_index('Names')[['year1','year2','year3']].T

print(df1)
          Joe     Doe
year1  240.87  243.72
year2    2.30    2.35
year3    0.85    0.84
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51