Python 按行索引分组的条形图 背景
我正在阅读Python机器学习入门,并在[45]中尝试了可视化。首先,我使用不同的Python 按行索引分组的条形图 背景,python,pandas,jupyter-notebook,seaborn,Python,Pandas,Jupyter Notebook,Seaborn,我正在阅读Python机器学习入门,并在[45]中尝试了可视化。首先,我使用不同的C参数将3个LogisticRegression分类器安装到Winsconsin癌症数据集。然后,对于每个分类器,我绘制了每个特征的系数大小 %matplotlib inline from sklearn.datasets import load_breast_cancer from sklearn.linear_model import LogisticRegression from matplotlib imp
C
参数将3个LogisticRegression
分类器安装到Winsconsin癌症数据集。然后,对于每个分类器,我绘制了每个特征的系数大小
%matplotlib inline
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from matplotlib import pyplot as plt
cancer = load_breast_cancer()
for C, marker in [(0.01, 'o'), (1., '^'), (100., 'v')]:
logreg = LogisticRegression(C=C).fit(cancer.data, cancer.target)
plt.plot(logreg.coef_[0], marker, label=f"C={C}")
plt.xticks(range(cancer.data.shape[1]), cancer.feature_names, rotation=90)
plt.hlines(0, 0, cancer.data.shape[1])
plt.legend()
在这种情况下,我更喜欢条形图而不是使用标记。我想得到一个图表,如:
我通过以下工作流程实现了这一点
步骤1:创建一个数据帧
将系数大小保持为一行
步骤2:将数据帧
转换为seaborn.barplot
-适用形式
步骤3:按seaborn.barplot进行绘图
这产生了我想要的图形
问题
我认为第二步很乏味。我可以直接从步骤1中的df
绘制条形图,还是通过一条直线绘制df\u条形图?或者是否有更优雅的工作流程来获取条形图?按列分组的条形图。因此,这应该是可能的
df = df.transpose()
df.plot(kind="bar")
不使用seaborn
如果出于任何原因需要使用seaborn,则可以通过pandas.melt
简化问题的第2步
df_bar = df.reset_index().melt(id_vars=["index"])
sns.barplot(x="variable", y="value", hue="index", data=df_bar)
熊猫图按列分组条形图。因此,这应该是可能的
df = df.transpose()
df.plot(kind="bar")
不使用seaborn
如果出于任何原因需要使用seaborn,则可以通过pandas.melt
简化问题的第2步
df_bar = df.reset_index().melt(id_vars=["index"])
sns.barplot(x="variable", y="value", hue="index", data=df_bar)
df_bar = df.reset_index().melt(id_vars=["index"])
sns.barplot(x="variable", y="value", hue="index", data=df_bar)