2

I have created a pandas dataframe object from a CSV file being read into a dataframe. The csv is very short and includes the following data:

Group Title, Hosts ,Soccer 5, Soccer 4, Soccer 3 , Soccer 2, Soccer 1, Soccer X ,Soccer Y, Soccer Total

Units,11,1,3,4,4,5,

[1 rows x 8 columns]

I have successfully displayed the data on a bar chart however I want the x axis to be labelled for each group title (Hosts, Socker 5, Socker 4 and so on) and plotted in alignment with the data

Please see a picture of my current graph below to get a better understanding

As you can see the X axis isn't labelled

I know I can do this manually but I want it to be read from the CSV file i.e the dataframe object. I have tried different methods to do this such as trying to add the following code

dataframe.plot.bar(dataframe['Group Title'], title="Soccer", ylabel="Quantity", xlabel="Devices")


My full code is below

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



dataframe = pd.read_csv('C:\Scripts\custom.csv', delimiter=",")

print(dataframe)

dataframe.plot()

#plt.rcParams['figure.figsize'] = (15,8)
matplotlib.style.use('ggplot')

dataframe.plot.bar(title="Devices", ylabel="Quantity", xlabel="Devices")


#Show Graphs
plt.show()

Any help or guidance will be appreciated. Thank you

1 Answer 1

2

You can use seaborn's barplot:

import seaborn as sns
import matplotlib.pyplot as plt
sns.barplot(data=df)
plt.xticks(rotation=45)

seaborn barplot

Alternatively, with pandas only:

df.set_index('Group Title').T.plot.bar()

pandas barplot

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

6 Comments

Hi when adding the following code: dataframe.set_index('Group Title').T.plot.bar() - it throws the error: line 4555, in set_index raise KeyError(f"None of {missing} are in the columns") KeyError: "None of ['Group Title'] are in the columns"
Then just remove the .set_index('Group Title') bit. It means that 'Group Title' is already the index in your case, which was not very clear in your question due to formatting.
Thanks this works. But my key on the top right corner is showing 0 now, instead of hosts, Soccer 5 and so on, any idea how I can get the key to show correctly?
I don't know what you mean. Don't you get the same as me? Can you post an image?
Yeah sure, so as you can see before I had the following key (please see top right corner of image) but now it just shows the key as 0 ibb.co/5M3w8P4
|

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.