2

I got this dataframe df,

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

table = {'Count_Product': pd.Series([1,2,3]), 'Count_Transaction': pd.Series([1,1,2])}
df = pd.DataFrame(table)
df

Count_Product   Count_Transaction
0   1   1
1   2   1
2   3   2

And I want to do a simple bar plot where the x axis is Count_Product and y axis is Count_Transaction. I used the following code to generate,

%matplotlib inline

ax = df['Count_Product'].plot(kind='bar', figsize=(5,5), color='blue')
ax.set_ylabel("Count_Transaction")
ax.set_xlabel("Count_Product")
patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='best')

And the graph output is,

enter image description here

My problem is the x-axis is showing 0,1,2 instead of 1,2,3 from the Count_Product column. It looks like it is taking the 1st column as the x-axis automatically.

Does anyone know how can I code the correct column to use the Count_Product column as the x-axis?

Thanks, Lobbie

1 Answer 1

3

I think you need first set_index from column Count_Product and then change df['Count_Product'].plot to df['Count_Transaction'].plot:

df = df.set_index('Count_Product')

ax = df['Count_Transaction'].plot(kind='bar', figsize=(5,5), color='blue')
ax.set_ylabel("Count_Transaction")
ax.set_xlabel("Count_Product")
patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='best')

graph

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

2 Comments

Hi Jezrael, thank you so much! I was thinking about I need to set an index somewhere and you showed me. Thanks again, Lobbie.
Yes, I also need to "change df['Count_Product'].plot to df['Count_Transaction'].plot". I also notice I do not need to do df['Count_Transaction'] and just use df.plot will also work. Thanks again.

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.