Coloring Scatter Plots by Column Values in Python
The versatility of ggplot2 in R allows for seamless assignment of colors to data points based on column values. This feature can also be replicated in Python using pandas dataframes and Matplotlib.
Using Pandas and Matplotlib
To map colors to values in Matplotlib, consider the following steps:
Here's an example implementation:
def dfScatter(df, xcol='Height', ycol='Weight', catcol='Gender'):
fig, ax = plt.subplots()
categories = np.unique(df[catcol])
colors = np.linspace(0, 1, len(categories))
colordict = dict(zip(categories, colors))
df["Color"] = df[catcol].apply(lambda x: colordict[x])
ax.scatter(df[xcol], df[ycol], c=df.Color)
return fig
Example Usage
Consider a dataframe with Height, Weight, and Gender columns. To create a scatter plot where colors are assigned based on the Gender column:
df = pd.DataFrame({'Height':np.random.normal(size=10),
'Weight':np.random.normal(size=10),
'Gender': ["Male","Male","Unknown","Male","Male",
"Female","Did not respond","Unknown","Female","Female"]})
fig = dfScatter(df)
This will generate a scatter plot where the Gender column determines the color of each data point.
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