如何以類別建立散佈圖
在Python的Matplotlib中,可以讓用plot方法來實現按類別建立散佈圖,如下所示:
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()
更客製化的外觀,類似於熊貓預設樣式:
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()
以上是如何在 Python 的 Matplotlib 中建立帶有分類資料的散佈圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!