1 回答
TA贡献1805条经验 获得超9个赞
你应该能够使用熊猫来绘制并避免循环:
from matplotlib.colors import LinearSegmentedColormap
colors = ['r','g','b','c','y','k']
lnst = ['-','--']
cats = np.sort(df['cat'].unique())
clusters = np.sort(df['cluster'].unique())
colordict = dict(zip(clusters, colors))
lnstdict = dict(zip(cats,lnst))
# transpose data frame
df1 = df.T
# map colors from colordict to cluster
cmap = df['cluster'].map(colordict).values.tolist()
# create a custom color map and line style
lscm = LinearSegmentedColormap.from_list('color', cmap)
lstyle = df['cat'].map(lnstdict).values.tolist()
# plot with pandas
df1.iloc[1:12].reset_index(level=0, drop=True).plot(figsize=(20,10),
colormap=lscm,
style=lstyle)
更新(假设您希望两者都在同一图表上)
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
%matplotlib inline
colors = ['r','g','b','c','y','k']
lnst = ['-','--']
cats = np.sort(df['cat'].unique())
clusters = np.sort(df['cluster'].unique())
colordict = dict(zip(clusters, colors))
lnstdict = dict(zip(cats,lnst))
# transpose data frame
df1 = df.T
# map colors from colordict to cluster
cmap = df['cluster'].map(colordict).values.tolist()
# create a custom color map and line style
lscm = LinearSegmentedColormap.from_list('color', cmap)
lstyle = df['cat'].map(lnstdict).values.tolist()
c = df.columns
# not needed for your actually dataframe
# i am just converting your sample data to numeric
for i in range(len(df.columns[1:])-1):
df[c[i+1]] = pd.to_numeric(df[c[i+1]])
# groupby and get mean of cluster
df2 = df[c[1:]].groupby('cluster').mean()
# create sublots object from matplotlib
fig, ax = plt.subplots()
# add a twin y-axis
ax2 = ax.twiny()
# plot dataframe 1
df1.iloc[1:12].reset_index(level=0, drop=True).plot(ax=ax, figsize=(20,10),
colormap=lscm,
style=lstyle)
# create legend for ax
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='center left', borderaxespad=-20)
# subplot df2
df2.plot(ax=ax2, colormap='copper')
# create legend for ax2
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels, loc='center right', borderaxespad=-20)
添加回答
举报