首页 > 解决方案 > Seaborn 中的对数

问题描述

我正在使用 seaborn 做箱形图,为此我使用以下代码

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.read_csv("Data_P64.txt", header=None, names=["val"])
df["cat"] = np.tile(np.repeat(["A", "B", "C"], 5), 7)
df["num1_5_10"] = np.repeat([1, 5, 10, 20, 30, 40, 50], 15)

ax = sns.boxplot(data=df, x="num1_5_10", y="val", hue="cat", zorder=0.9, dodge=False)
#add the lines connecting the median values
sns.pointplot(data=df, x="num1_5_10", y="val", hue="cat", estimator=np.median, ci=None, markers="None", ax=ax)


#remove duplicate entries, setting the legend outside the graph, new title
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:3], labels[:3], bbox_to_anchor=(1, 1), title="C++ for the win")
plt.tight_layout()
plt.show()

但我想要做的是,对于 Y 轴,我想取logarithmY 值中的一个。如何在这里做到这一点?

这是正确的方法吗?

df = pd.read_csv("Data_P64.txt", header=None, names=["val"])
df["cat"] = np.tile(np.repeat(["A", "B", "C"], 5), 7)
df["num1_5_10"] = np.repeat([1, 5, 10, 20, 30, 40, 50], 15)

df['val_log'] = np.log2(df['val'].values)

ax = sns.boxplot(data=df, x="num1_5_10", y="val_log", hue="cat", zorder=0.9, dodge=False)

标签: pythonmatplotlibseaborn

解决方案


我认为您可以通过以下方式创建另一个名为 val_log 的列:

df['val_log'] = np.log(df['val'].values)

并创建情节:

ax = sns.boxplot(data=df, x="num1_5_10", y="val_log", hue="cat", zorder=0.9, dodge=False)

推荐阅读