'How to solve error with limits in boxplot (seaborn)?

The code used to plot the box plot:

import seaborn as sns
ax= sns.boxplot(x = "Current_Sim_Az_obj1",y= "RUT_Distance",data = df2,whis = (0,100),meanline= True,showmeans=True)
ax.set_title('TEST 3.1 boxplot')
ax.figsize = (12, 10)
ax.set_xlabel('Current_Sim_Azimuth[°]')
ax.set_ylabel('RUT_Distance[m]')

The figure i received after this is enter image description here

Now i changed the xlimits and ylimits.The code is added below

pl.grid()
ax.set(xlim=(-60,60), xticks=np.arange(-60, 63,5),ylim=(3,100), yticks=np.arange(0,103,5))

the result was: enter image description here

Why this is so?The x limits are wrong.

How to solve this issue?
Also,Instead of median line in box plot i want to get a darker mean line or a point and want to remove the box(for example:something like this instead of box |-----x-----|)



Solution 1:[1]

To remove the .0 from the xticks, the easiest is to convert the corresponding column from float to integer. Note that for boxplots (and e.g. barplots), seaborn creates a categorical axis, also for numeric data. Internally, the axis is numbered 0,1,2,.... To change the xlim, you can extract the current limits and add a bit (0.4 would be 40% of the distance between the boxes).

To "remove" the boxes, you could make them very narrow. (width=0 would reduce them to a line). A drawback could be that also the end caps are reduced in length.

You can change the properties of the mean via meanprops={...}. The mean is represented by a Line2D.

Note that sns.boxplot() parameters that aren't caught by seaborn are sent to ax.boxplot().

To change the figsize, e.g. plt.figure(figsize=...) can be used (to be called before creating the plot).

Here is an example. Many variations are possible.

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df2 = pd.DataFrame({"Current_Sim_Az_obj1": np.random.choice(np.arange(-60, 61, 5.0), 1000),
                    "RUT_Distance": np.random.randn(1000).cumsum()})
df2["RUT_Distance"] += np.cos(df2["Current_Sim_Az_obj1"] / 50) * 50
df2["Current_Sim_Az_obj1"] = df2["Current_Sim_Az_obj1"].astype(int)
plt.figure(figsize=(12, 7))
sns.set_style('whitegrid')
ax = sns.boxplot(x="Current_Sim_Az_obj1", y="RUT_Distance", data=df2, whis=(0, 100), width=0.1,
                 boxprops={'facecolor': 'black'},
                 showmeans=True, meanline=False, meanprops={'marker': 'o', 'mfc': 'white', 'mec': 'black', 'ms': 10})
xmin, xmax = ax.get_xlim()
ax.set_xlim(xmin - 0.4, xmax + 0.4)
sns.despine(left=True)
plt.tight_layout()
plt.show()

sns.boxplot with narrow boxes

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1