Margin Boxplots Matplotlib
我想手动为以下代码生成的箱线图添加一个边距。目前箱线图中的角(端)太多。一般来说,会有许多箱线图(与此示例代码不同),我希望这些箱线图的间距相等(如代码中所示),但我希望在两侧留有边距 我使用的是matplotlib版本1.3.1Margin Boxplots Matplotlib,matplotlib,margin,boxplot,Matplotlib,Margin,Boxplot,我想手动为以下代码生成的箱线图添加一个边距。目前箱线图中的角(端)太多。一般来说,会有许多箱线图(与此示例代码不同),我希望这些箱线图的间距相等(如代码中所示),但我希望在两侧留有边距 我使用的是matplotlib版本1.3.1 如果ax.margins()没有按预期工作,下面是一个黑客解决方法 import numpy as np import matplotlib.pyplot as plt statistic_dict = {0.40: [0.36, 0.40, 0.46],
如果
ax.margins()
没有按预期工作,下面是一个黑客解决方法
import numpy as np
import matplotlib.pyplot as plt
statistic_dict = {0.40: [0.36, 0.40, 0.46],
0.20: [0.11, 0.23, 0.12],
0.70: [0.19, 0.23, 0.12]}
def draw_boxplot(y_values, x_values, edge_color, fill_color):
bp = plt.boxplot(y_values, patch_artist=True, positions=x_values)
for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(bp[element], color=edge_color)
plt.xlabel("x label ")
plt.ylabel("y label ")
plt.title("Title")
for patch in bp['boxes']:
patch.set(facecolor=fill_color)
v = np.array([box.get_path().vertices for box in bp['boxes']])
margin=0.2
xmin = v[:,:5,0].min() - (max(x_values)-min(x_values))*margin
xmax = v[:,:5,0].max() + (max(x_values)-min(x_values))*margin
plt.xlim(xmin, xmax)
y_values = statistic_dict.values()
x_values = statistic_dict.keys()
draw_boxplot(y_values, x_values, "skyblue", "white")
plt.show()
Matplotlib 1.3.1的使用年限超过4年。我可以推荐升级,这样解决方案就可以了。升级时我遇到了一些问题。。。。
import numpy as np
import matplotlib.pyplot as plt
statistic_dict = {0.40: [0.36, 0.40, 0.46],
0.20: [0.11, 0.23, 0.12],
0.70: [0.19, 0.23, 0.12]}
def draw_boxplot(y_values, x_values, edge_color, fill_color):
bp = plt.boxplot(y_values, patch_artist=True, positions=x_values)
for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(bp[element], color=edge_color)
plt.xlabel("x label ")
plt.ylabel("y label ")
plt.title("Title")
for patch in bp['boxes']:
patch.set(facecolor=fill_color)
v = np.array([box.get_path().vertices for box in bp['boxes']])
margin=0.2
xmin = v[:,:5,0].min() - (max(x_values)-min(x_values))*margin
xmax = v[:,:5,0].max() + (max(x_values)-min(x_values))*margin
plt.xlim(xmin, xmax)
y_values = statistic_dict.values()
x_values = statistic_dict.keys()
draw_boxplot(y_values, x_values, "skyblue", "white")
plt.show()