如何从图中的列名中删除下划线?

How to remove underscores from column names within plots?

我正在处理在列名称中将下划线作为空格的数据框。据我了解,这是一个很好的做法,所以我不想用空格重命名列。

绘制各个列之间的相关性时,列名在图中用下划线拼出。我希望能够使用空格代替更清晰的阅读视觉效果。

有没有办法修改图表中显示的名称,以便我可以用空格替换所有下划线 and/or 将这些图表中显示的标签重命名为 different/more 比实际列名?目前我的绘图使用 matplotlib 和 seaborn。

编辑: 要添加更多关于我这样做的原因的详细信息 - 我正在从 SQL 查询构建此数据框。 SQL 数据库的列名中有下划线,所以在这里继承。下面一个有用的答案是重命名生成的数据框以用空格替换下划线。另一个我刚刚想到的是在进行查询时将列导入为更易读的名称。如果我想通过添加详细信息,这还允许我更改列以使其更加清晰。

SELECT table.column_name AS [Column Name]

但这留下了我的另一个问题 - 为什么在 SQL 数据库的列名中不包含空格很重要?从理论上讲,我可以做到这一点,这样数据库就有了我想要的内置空间。

我发现 <your_col_name_here>.replace("_", " ").title() 对此很有帮助。

这里有一些例子...

示例 1 - Matplotlib:

def show_iris_histograms():
    cols_to_plot = [
        "sepal_length",
        "sepal_width",
        "petal_length",
        "petal_width",
]
    fig = plt.figure(figsize=(10, 6))
    for i, col_name in enumerate(cols_to_plot):
        ax = fig.add_subplot(2, 2, i + 1)
        iris[col_name].hist(bins=15, ax=ax)
        col_name_label = col_name.replace("_", " ").title()
        ax.set_title(col_name_label + " Distribution")
    fig.tight_layout()
    plt.show()

show_iris_histograms()

输出:

示例 2 - Seaborn:

def show_iris_pairplots():
    pair_plot = sns.pairplot(iris, hue="class")
    pair_plot.fig.get_children()[-1].set_title("Class")
    for i in range(4):
        for j in range(4):
            x_label = pair_plot.axes[i][j].get_xlabel()
            y_label = pair_plot.axes[i][j].get_ylabel()
            pair_plot.axes[i][j].set_xlabel(
                x_label.replace("_", " ").title(),
            )
            pair_plot.axes[i][j].set_ylabel(
                y_label.replace("_", " ").title(),
            )
plt.show()

show_iris_pairplots()

输出:

如果将整个数据框传递给绘图方法

使用pandas rename方法和Python的字符串replace一起用空格替换下划线。

一种方法是使用修改后的列名称创建一个辅助数据框,并将该新数据框传递给绘图方法,例如:

import pandas as pd

# Dummy df
df = pd.DataFrame({
    'Column_1': pd.Series([1, 2, 3]), 
    'Column_2': pd.Series([1, 2, 3]),
    'Column_3': pd.Series([1, 2, 3]),
})

modified_df = df.rename(columns=lambda name: name.replace('_', ' '))

print(df)
print(modified_df)

输出:

   Column_1  Column_2  Column_3
0         1         1         1
1         2         2         2
2         3         3         3
   Column 1  Column 2  Column 3
0         1         1         1
1         2         2         2
2         3         3         3

如果你不介意改变原始数据框,你可以做这个操作inplace,而不需要创建辅助数据框:

df.rename(columns=lambda name: name.replace('_', ' '), inplace=True)

如果您只需要一个带有修改标签的列表

您可以使用列表理解生成新标签:

labels = [col.replace('_', ' ') for col in df.columns]