R plotly:在方框图中自定义x轴值

时间:2016-11-16 23:20:36

标签: r plotly

我有一个包含3个变量和260行的数据框。 (以下示例)

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 

我想根据城镇频率的降序为x轴的顺序创建一个箱形图,用于分布乘客

Town Freq
A    3
B    2
C    4
D    1

(示例图片)

Sample Boxplot

我尝试对数据框进行排序,但是,默认情况下,框图x轴基于字母顺序显示。有没有办法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

您只需使用factor根据计数df$Town重新排序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