0

Very new to coding, so please excuse the lack of finesse. I will try to describe my problem as best as I can.

I have a tabular list of 'City_names' and 'Year_spending', and would like to create plots of spending versus time (Year), color coded by city_names. How would I best approach this in Pandas?

This is the current format of my table:

City_names Year_2000_spending Year_2002_spending Year_2003_spending
City 1 $1 $5 $1
City 2 $8 $7 $7
City 3 $5 $3 $9
mozway
  • 194,879
  • 13
  • 39
  • 75
shb2013
  • 3
  • 1
  • Does this answer your question? [Pandas dataframe groupby plot](https://stackoverflow.com/questions/41494942/pandas-dataframe-groupby-plot) – 404pio Feb 14 '22 at 12:30

1 Answers1

0

You could start with this. This gives a bar graph of spending versus time (Year), color coded by city_names, as shown below.

enter image description here

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame([['City 1', '$1', '$5', '$1'],['City 2', '$8', '$7', '$7'],['City 3', '$5', '$3', '$9']], columns=['City_names', 'Year_2000_spending', 'Year_2002_spending', 'Year_2003_spending'])
df=df.replace('\$','',regex=True)
df[['Year_2000_spending', 'Year_2002_spending', 'Year_2003_spending']] = df[['Year_2000_spending', 'Year_2002_spending', 'Year_2003_spending']].apply(pd.to_numeric)
df = df.set_index('City_names')
df = df.T.reset_index()

df.plot.bar(x='index')
plt.xticks(rotation=0, ha='right')
plt.show()
Manjunath K Mayya
  • 1,078
  • 1
  • 11
  • 20
  • Thanks for sharing. I tried this to the letter, but keep getting this error message "no numeric data to plot" even though line 3 of the code converts to numeric. Any idea why that would be? – shb2013 Feb 14 '22 at 18:35
  • If you update the question with your data and code, It would help us in trying to resolve your issue. – Manjunath K Mayya Feb 15 '22 at 02:16
  • I was able to figure out the issue. Somehow, the executing the following code kept converting the dtype back to 'object': df = df.T.reset_index(). I was able to re-convert to numeric and plot the graph. Thanks again for your guidance! – shb2013 Feb 16 '22 at 09:14