关于Seaborn直方图标签错误及展示样式调整的技术咨询
关于Seaborn直方图标签错误及展示样式调整的技术咨询
Hey there! Let's work through fixing your Seaborn plot to get exactly what you want—proper labels and line-only styling for both Bot and Human accounts.
First, let's break down the issues you're facing:
- The legend has mismatched markers (a box and a line) instead of consistent line markers
- You want both groups to display as lines (no filled areas) with distinct colors
- The label alignment might be off if the order doesn't match your data's
botcolumn values
Here's the revised code with explanations for each change:
import matplotlib.pyplot as plt from matplotlib.lines import Line2D import seaborn as sns plt.figure(figsize=(7,5), dpi=100) # Core plot setup: Remove fill to show only lines, disable auto-legend sns.histplot( x='hour_created', data=training1_data, hue='bot', kde=True, stat='density', common_bins=True, element='step', fill=False, # 关键改动:去掉填充区域,只保留线条 legend=False # 关闭Seaborn自动图例,避免标记冲突 ) # Create custom legend with line markers (instead of boxes) # Use Seaborn's default color palette to match plot colors custom_legend = [ Line2D([0], [0], color=sns.color_palette()[0], lw=2), Line2D([0], [0], color=sns.color_palette()[1], lw=2) ] # Adjust labels here to match your data's bot category order! # Run `print(training1_data['bot'].unique())` to check the order of values plt.legend( custom_legend, ['Bot', 'Human'], title='Account Type', loc='best' ) # Keep your original plot formatting plt.title("Time of Day Account was Created", fontsize=12) plt.xlabel('Time of Day (24h)', fontsize=10) plt.ylabel('Density', fontsize=10) plt.xlim(0, 24) plt.ylim(0, 0.05) sns.despine() # plt.savefig('imgs/hour_created.png');
Key fixes explained:
- Line-only display: Adding
fill=Falseremoves the colored fill under the step histogram, so both the histogram and KDE lines are visible without any filled boxes—exactly what you asked for. - Consistent legend markers: By creating custom Line2D objects for the legend, we replace the default box markers with line markers, so both entries in the legend match the plot's line style.
- Label alignment: Double-check the order of
['Bot', 'Human']against your data'sbotcolumn. If you runprint(training1_data['bot'].unique()), you'll see the order Seaborn uses for hue—adjust the labels inplt.legend()if they're reversed.
That should get your plot looking exactly how you want it!
备注:内容来源于stack exchange,提问作者WT YXK
相关产品推荐
相关产品推荐

