在同一图表上绘制matplotlib图(中位数回归)和pandas boxplot [英] plot matplotlib plot (regression of medians) and pandas boxplot on the same chart
问题描述
我想在同一轴上绘制箱线图(熊猫)和中位数的回归.不幸的是,它不能按预期工作.都没有
fig,ax = plt.subplots(ncols = 1)data.boxplot(xxx,ax = ax)ax.plot(xreg,yreg)
也没有
fig,ax = plt.subplots(ncols = 1)bplot = data.boxplot(xxx, ax=ax)bplot.plot(xreg,yreg)
似乎可以正常工作.
最后一种方法似乎工作得更好.x不一致.任何想法可能是什么原因以及如何在两个轴上获得相同的比例?
fig,ax = plt.subplots(ncols = 1)ax1 = ax.twiny()bplot = data.boxplot(xxx,ax = ax)ax1.plot(xreg, yreg)
原因可能是轴的缩放:
ax.get_xlim()(0.5、4.5)ax1.get_xlim()(-4.0, 84.0)
如果我只绘制回归曲线和中位数而没有箱线图,那么一切都很好:
通过查看
I would like to plot a boxplot (pandas) and the regression of the medians on the same axes. Unfortunately, it does not work as expected. Neither
fig, ax = plt.subplots(ncols=1)
data.boxplot(xxx, ax=ax)
ax.plot(xreg, yreg)
nor
fig, ax = plt.subplots(ncols=1)
bplot = data.boxplot(xxx, ax=ax)
bplot.plot(xreg, yreg)
seems to work.
The last approach seems to work slighty better The x does not fit together. Any ideas what might be the reason and how to get the same scale ob both axis ?
fig, ax = plt.subplots(ncols=1)
ax1 = ax.twiny()
bplot = data.boxplot(xxx, ax=ax)
ax1.plot(xreg, yreg)
The reason is probably the scaling of the axis:
ax.get_xlim()
(0.5, 4.5)
ax1.get_xlim()
(-4.0, 84.0)
If I just plot the regression and the medians without the boxplot, everything works fine:
By looking at the documentation of plt.boxplot
, we find that the boxes are located by default at indexing positions 0,1,2,.. . The axes limits for N boxes are thus [-0.5, N+0.5].
The documentation tells us as well that the locations of the boxes can be changed using the positions
argument.
Using this argument, we can position the boxes at any place along the x axis, and might then want to adapt their width, if their separation becomes very large or small.
Complete example:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,70)
f = lambda x: 6*np.exp(-x/50.)
pos = [10, 40, 48, 64]
a = np.empty((100,len(pos)))
for i, p in enumerate(pos):
a[:,i] = np.random.normal(loc=f(p), size=a.shape[0])
plt.boxplot(a, positions=pos, widths=5)
plt.plot(x, f(x))
plt.xlim(0,70)
plt.show()
这篇关于在同一图表上绘制matplotlib图(中位数回归)和pandas boxplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!