python - Seaborn 中的自定义图表格式
问题描述
我在 seaborn 中有一个简单的计数图。
代码是:
ax = sns.countplot(x="days", data=df,color ='cornflowerblue')
ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
ax.set(xlabel='days', ylabel='Conversions')
ax.set_title("Days to Conversion")
for p in ax.patches:
count = p.get_height()
x = p.get_x() + p.get_width()/1.25
y = p.get_height()*1.01
ax.annotate(count, (x, y),ha='right')
产生:
我试图让图表更“漂亮”。具体来说,我想提高轮廓的高度,这样它就不会越过第一个条上的计数,并使计数以条的小空间居中。无法让它工作。
请指导。
解决方案
要设置标签,在最新的 matplotlib 版本(3.4.2)中,有一个新功能bar_label()
可以处理定位。在旧版本中,您可以使用您的代码,但使用x = p.get_x() + p.get_width()/2
并设置ax.text(..., ha='center')
.
为了给标签腾出空间,可以通过添加额外的边距ax.margins(y=0.1)
。
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('tips')
ax = sns.countplot(x="day", data=df, color='cornflowerblue')
ax.tick_params(axis='x', labelrotation=90)
ax.bar_label(ax.containers[-1])
ax.margins(y=0.1)
plt.tight_layout()
plt.show()
推荐阅读
- fmod - 从 FMOD Designer 转换到 FMOD Studio 时设置音高值
- python - 连接到在单独的类中定义的函数
- python - 在python pandas中识别线在一个方向上相交的点
- css - 具有最大高度的可扩展文本区域,仅使用 css
- javascript - 为什么正则表达式匹配很慢?
- java - 将助记符 MARC 转换为常规 MARC
- c# - 如何在统一 c# 中使用 itext7 将图像添加到 pdf?
- linux - 如何在 Dockerfile 中运行 sudo su -
- ios - 后台位置更新因调试器中发现的后台任务问题而停止
- node.js - 在运行时更改 ENV 变量