如何使用给定三列数据制作颜色编码散点图?
Color-Coded Scatter Plot for Member Demographics
Got it, let's tackle this visualization request. First, I notice the original data you shared has mismatched lengths—member_birth_year has 13 entries, but member_gender and user_type only have 3 and 2 respectively. I'll start by generating a properly aligned synthetic dataset that uses your specified categories, then walk through two straightforward ways to build the color-coded scatter plot.
Step 1: Prepare Aligned Data
First, let's create a consistent dataset where every birth year has a corresponding gender and user type:
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Use your birth year list, then generate matching gender/user type values birth_years = [1890, 1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010] genders = np.random.choice(['male','female', 'other'], size=len(birth_years)) user_types = np.random.choice(['customer', 'subscriber'], size=len(birth_years)) # Package into a DataFrame for easy handling data = pd.DataFrame({ 'member_birth_year': birth_years, 'member_gender': genders, 'user_type': user_types })
Option 1: Matplotlib (Full Control Over Colors)
This approach lets you define exact colors for each category:
plt.figure(figsize=(10,6)) # Define custom color mapping for user types color_map = {'customer': '#2ca02c', 'subscriber': '#ff9896'} # Plot each user type group with its own color for user_type, group in data.groupby('user_type'): # Add random jitter to y-axis to avoid overlapping points plt.scatter(group['member_birth_year'], np.random.normal(0, 0.4, size=len(group)), label=user_type, color=color_map[user_type], alpha=0.8, s=90) # Customize plot labels and styling plt.xlabel('Member Birth Year', fontsize=12) plt.ylabel('Jittered Y-Axis (for readability)', fontsize=12) plt.title('Birth Year vs User Type (Color-Coded)', fontsize=14) plt.legend(title='User Type') plt.grid(alpha=0.3) plt.show()
Option 2: Seaborn (Simpler Categorical Coloring)
Seaborn automatically handles categorical color mapping, which cuts down on boilerplate code:
plt.figure(figsize=(10,6)) # Scatter plot with color coded by member_gender (swap to 'user_type' if needed) sns.scatterplot(data=data, x='member_birth_year', y=np.random.normal(0, 0.4, size=len(data)), hue='member_gender', palette='coolwarm', alpha=0.8, s=90) # Polish the plot plt.xlabel('Member Birth Year', fontsize=12) plt.ylabel('Jittered Y-Axis (for readability)', fontsize=12) plt.title('Birth Year vs Gender (Color-Coded)', fontsize=14) plt.grid(alpha=0.3) plt.show()
Quick Notes:
- The random jitter on the y-axis is crucial here—without it, all points would stack on top of each other since birth years are discrete. If you have a real numerical y-variable, just replace
np.random.normal(0, 0.4, ...)with that column. - To switch which category defines the color, just swap
hue='member_gender'(Seaborn) or the groupby key (Matplotlib) touser_type. - Adjust
sto change point size,alphato tweak transparency, andpalette/color_mapto pick your preferred color scheme.
内容的提问来源于stack exchange,提问作者Rick J
相关产品推荐
相关产品推荐

