How to Create a Scatter Plot by Category
In Python's Matplotlib, creating a scatter plot by category can be achieved using the plot method, as demonstrated below:
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Generate Data num = 20 x, y = np.random.random((2, num)) labels = np.random.choice(['a', 'b', 'c'], num) df = pd.DataFrame(dict(x=x, y=y, label=labels)) # Group Data groups = df.groupby('label') # Plot fig, ax = plt.subplots() ax.margins(0.05) # Optional padding for name, group in groups: ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name) ax.legend() plt.show()
For a more customized appearance resembling Pandas' default style:
import matplotlib.pyplot as plt import numpy as np import pandas as pd # Generate Data num = 20 x, y = np.random.random((2, num)) labels = np.random.choice(['a', 'b', 'c'], num) df = pd.DataFrame(dict(x=x, y=y, label=labels)) # Group Data groups = df.groupby('label') # Plot plt.rcParams.update(pd.tools.plotting.mpl_stylesheet) colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random') fig, ax = plt.subplots() ax.set_color_cycle(colors) ax.margins(0.05) for name, group in groups: ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name) ax.legend(numpoints=1, loc='upper left') plt.show()
The above is the detailed content of How to Create a Scatter Plot with Categorical Data in Python\'s Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!