-1

I would like to plot my data using a scatter plot. I have tried to use the following code:

DF.groupby('Title').plot(x = 'Total',y = 'Rating', kind='scatter')

It works but it gives me two plots - one for each group. What I would like instead is one plot with the data from the two groups together but with different colours, e.g. group one in red and goup 2 in green. Is that possible? Thanks for your help :)

Laily
  • 11
  • 3
  • This question needs a [SSCCE](http://sscce.org/). Please see [How to ask a good question](https://stackoverflow.com/help/how-to-ask). Always provide a complete [mre] with **code, data, errors, current output, and expected output**, as **[formatted text](https://stackoverflow.com/help/formatting)**. If relevant, only plot images are okay. If you don't include an mre, it is likely the question will be downvoted, closed, and deleted. – Trenton McKinney Nov 04 '21 at 22:07
  • Provide an example of the raw dataframe before groupby – Trenton McKinney Nov 04 '21 at 22:08

2 Answers2

0

In this case, you don't want to aggregate values, so you don't need to use groupby. Instead, you can draw scatter plot like this as you want:

import pandas as pd
  
data={
    'x':[1, 2, 3, 4, 5, 6],
    'y':[3, 6, 9, 3, 6, 9],
    'title': [1, 1, 1, 2, 2, 2]
     }

df = pd.DataFrame(data)

print(df)
'''
   x  y  title
0  1  3      1
1  2  6      1
2  3  9      1
3  4  3      2
4  5  6      2
5  6  9      2
'''

ax = df[df['title']==1].plot(x="x", y="y", color="Red", label="Title 1", kind='scatter')
df[df['title']==2].plot(x="x", y="y", color="Green", label="Title 2", kind='scatter', ax=ax)

enter image description here

With seaborn library, you can do more things in very convenient ways (see https://seaborn.pydata.org/generated/seaborn.scatterplot.html).

Park
  • 2,446
  • 1
  • 16
  • 25
-1
import matplotlib.pyplot as plt
for i,j in df.groupby("Title"):
    plt.scatter(j.Total,j.Rating,label=i)
    plt.legend(loc="best")
  • 2
    Thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. – Jeremy Caney Nov 05 '21 at 00:26