python - matplotlib boxplot 与覆盖散点图不对齐
问题描述
我有一个情节,我试图在箱线图系列上叠加一个散点系列......这是一个简单的问题示例,以便您可以重新创建它。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
names = ['a','b','c','d','e','f']
df = pd.DataFrame(np.random.rand(6,6), columns=names)
display(df)
plt.boxplot(df, labels=names)
plt.show()
plt.scatter(names, df.head(1))
plt.show()
plt.boxplot(df, labels=names)
plt.scatter(names, df.head(1))
plt.show()
结果:
所以你会看到,当箱线图和散点图都添加到同一个图中时,标签不再正确对齐。如何修复这种对齐方式?
解决方案
- 在
python 3.8.11
,pandas 1.3.2
,matplotlib 3.4.3
,中测试seaborn 0.11.2
- 请注意
xticklabel
位置未对齐。 - 根据
matplotlib.pyplot.boxplot
,position
默认为range(1, N+1)
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(6, 8))
ax1.boxplot(df, labels=names)
print(ax1.get_xticks())
ax2.scatter(names, df.head(1))
print(ax2.get_xticks())
ax3.boxplot(df, labels=names)
ax3.scatter(names, df.head(1))
[out]:
[1 2 3 4 5 6]
[0, 1, 2, 3, 4, 5]
- 给定现有代码,正确的解决方案是设置
positions
参数 pandas.DataFrame.melt
对于散点图,这还需要使用 , 将数据框转换为长格式。
plt.boxplot(df, labels=names, positions=range(len(df.columns)))
plt.scatter(data=df.melt(), x='variable', y='value')
- 或者,直接用
pandas.DataFrame.plot
ax = df.plot(kind='box', positions=range(len(df.columns)))
df.melt().plot(kind='scatter', x='variable', y='value', ax=ax)
- 最简单的解决方案是使用
seaborn
,它是matplotlib
. 这直接绘制给定的数据框,没有任何转换 .boxplot
位置从 0 开始
import seaborn as sns
sns.boxplot(data=df, boxprops={'facecolor':'None'})
print(plt.xticks())
sns.swarmplot(data=df)
print(plt.xticks())
[out]:
(array([0, 1, 2, 3, 4, 5]), [Text(0, 0, 'a'), Text(1, 0, 'b'), Text(2, 0, 'c'), Text(3, 0, 'd'), Text(4, 0, 'e'), Text(5, 0, 'f')])
(array([0, 1, 2, 3, 4, 5]), [Text(0, 0, 'a'), Text(1, 0, 'b'), Text(2, 0, 'c'), Text(3, 0, 'd'), Text(4, 0, 'e'), Text(5, 0, 'f')])
推荐阅读
- javascript - 如何在js中使用另一个div属性值更改div背景颜色
- database - Cloud Firestore 结构更好的案例
- angular - 如何根据anular中的复选框值过滤firebase数据库
- server - WAMP 服务器指向 IP 地址,现在 IP 地址已更改。我无法再访问我的网站
- java - 服务发送的通知不会显示
- javascript - 返回带有异步请求的布尔值
- excel - 有一个 UDF 来执行 countif 并“评分”一行
- java - Jersey:使用 REST API 上传文件失败,HTTP 状态 415 – 不支持的媒体类型
- android - 在水平滚动视图的回收器视图中显示超过 5 列
- xamarin - 使用动态资源或指定确切数字的 Xamarin Forms 的 Android 绘制性能?