Jessie Jessie - 9 months ago 61
R Question

R plotly: Customize x-axis values in box plot

I have a data frame with 3 variables and 260 rows. (Sample below)


HouseID Town Occupants
1 D 5
2 A 3
3 B 2
4 C 4
5 A 5
6 B 2
7 C 3
8 C 8
9 C 1
10 A 3

I want to create a box plot for the distribution of Occupants with the order of x-axis based on the descending order of frequencies of Towns

Town Freq
A 3
B 2
C 4
D 1

(Shown a sample image)

Sample Boxplot

I tried sorting the data frame, but still, the box plot x-axis is displayed based on alphabetical order by default. Is there a way I could do this?

Answer Source

You simply have to use factor to reorder levels of df$Town according to their count summary(df$Town):

df$Town <- factor(df$Town, levels(df$Town)[order(summary(df$Town),decreasing = TRUE)])
plot_ly(df, x=~Town, y=~Occupants, type="box")

enter image description here