1

Having a DataFrame structured as follows:

                 A            B
country       C     D     C      D
Albany      2.05    4    1.85    4
China       2.67    3    1.21    3
Portugal    1.44    6    2.34    6
France      5.83    3    2.50    3
Greece      0.63    6    3.02    6

I don't know how can I make a scatter plot where, choosing A or B, gives me a scatter with x=C and y=D for every country. If I do it like this it gives me a KeyError:

df.plot.scatter(x='C', y='D')

Any suggestions?

Many thanks!

1 Answer 1

1

You can group over the 0th level of the columns to plot each separately. Grouping only splits the DataFrame, it doesn't modify anything so you can either use tuples as the keys or use DataFrame.xs to remove the now redundant MultiIndex level.

for idx, gp in df.groupby(level=0, axis=1):
    gp.xs(idx, level=0, axis=1).plot.scatter(x='C', y='D', title=idx)

enter image description here enter image description here


Or if you want one plot:

import matplotlib.pyplot as plt

cd = {'A': 'red', 'B':'blue'}  # color by group

fig, ax = plt.subplots()
for idx, gp in df.groupby(level=0, axis=1):
    gp.xs(idx, level=0, axis=1).plot.scatter(x='C', y='D', ax=ax, label=idx, c=cd[idx])

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.