简体   繁体   English

R绘图:在箱形图中自定义x轴值

[英]R plotly: Customize x-axis values in box plot

I have a data frame with 3 variables and 260 rows. 我有一个包含3个变量和260行的数据框。 (Sample below) (以下示例)

HouseID<-c(1:10)
Town<-c("D","A","B","C","A","B","C","C","C","A")
Occupants<-c(5,3,2,4,5,2,3,8,1,3)
df<-data.frame(HouseID,Town,Occupants)

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 我想根据城镇频率的降序创建一个用于x轴顺序的乘员分布的箱形图

Town Freq
A    3
B    2
C    4
D    1

(Shown a sample image) (显示示例图片)

样品箱图

I tried sorting the data frame, but still, the box plot x-axis is displayed based on alphabetical order by default. 我尝试对数据框进行排序,但是默认情况下,箱形图x轴是根据字母顺序显示的。 Is there a way I could do this? 有办法吗?

You simply have to use factor to reorder levels of df$Town according to their count summary(df$Town) : 您只需要使用factor根据其计数summary(df$Town)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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM