To create a scatter plot where different categorical levels are represented by different colors using Matplotlib, follow these steps:
import matplotlib.pyplot as plt
import pandas as pd
colors = {'D':'tab:blue', 'E':'tab:orange', 'F':'tab:green', 'G':'tab:red', 'H':'tab:purple', 'I':'tab:brown', 'J':'tab:pink'}
df.scatter(df['carat'], df['price'], c=df['color'].map(colors))
plt.show()
Seaborn is a wrapper around Matplotlib that provides a more user-friendly interface. To create a scatter plot with different colors for categorical levels using Seaborn, follow these steps:
import seaborn as sns
sns.scatterplot(x='carat', y='price', data=df, hue='color')
plt.show()
You can also use pandas.groupby and pandas.DataFrame.plot to create a scatter plot with different colors for categorical levels. This method requires more manual work, but it gives you more control over the plot's appearance.
import pandas as pd
fig, ax = plt.subplots(figsize=(6, 6))
grouped = df.groupby('color')
for key, group in grouped:
group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])
plt.show()
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3