4

My DataFrame's structure

trx.columns
Index(['dest', 'orig', 'timestamp', 'transcode', 'amount'], dtype='object')

I'm trying to plot transcode (transaction code) against amount to see the how much money is spent per transaction. I made sure to convert transcode to a categorical type as seen below.

trx['transcode']
...
Name: transcode, Length: 21893, dtype: category
Categories (3, int64): [1, 17, 99]

The result I get from doing plt.scatter(trx['transcode'], trx['amount']) is

Scatter plot

While the above plot is not entirely wrong, I would like the X axis to contain just the three possible values of transcode [1, 17, 99] instead of the entire [1, 100] range.

Thanks!

1
  • Look at a box plot, violin plot, or bar plot. Commented Nov 13, 2017 at 17:16

1 Answer 1

8

In matplotlib 2.1 you can plot categorical variables by using strings. I.e. if you provide the column for the x values as string, it will recognize them as categories.

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

df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                   "y" : np.random.rand(100)*100})

plt.scatter(df["x"].astype(str), df["y"])
plt.margins(x=0.5)
plt.show()

enter image description here

In order to optain the same in matplotlib <=2.0 one would plot against some index instead.

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

df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                   "y" : np.random.rand(100)*100})

u, inv = np.unique(df["x"], return_inverse=True) 
plt.scatter(inv, df["y"])
plt.xticks(range(len(u)),u)
plt.margins(x=0.5)
plt.show()

The same plot can be obtained using seaborn's stripplot:

sns.stripplot(x="x", y="y", data=df) 

And a potentially nicer representation can be done via seaborn's swarmplot:

sns.swarmplot(x="x", y="y", data=df)

enter image description here

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

Comments

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.