堆积条由填充总和与ggplot2排序

时间:2016-03-10 16:10:15

标签: r ggplot2

使用以下数据(已经融化的数据框):

df1<-structure(list(Speciality = structure(27:32, .Label = c("Addiction Medicine", 
    "Anesthesiology", "Cardiac Electrophysiology", "Cardiology", 
    "Dermatology", "Emergency Medicine", "Family Medicine", "Gastroenterology", 
    "General Surgery", "Hematology & Oncology", "Hospitalist", "Internal Medicine", 
    "Nephrology", "Neurological Surgery", "Neurology", "Obstetrics & Gynecology", 
    "Otolaryngology", "Pain Medicine", "Pathology", "Pediatric Critical Care Medicine", 
    "Pediatric Hematology-Oncology", "Pediatric Pulmonology", "Pediatric Radiology", 
    "Pediatric Surgery", "Pediatrics", "Psychiatry", "Pulmonology", 
    "Radiation Oncology", "Radiology", "Surgical Oncology", "Urology", 
    "Vascular Surgery"), class = "factor"), PhysAge = structure(c(5L, 
    5L, 1L, 3L, 5L, 5L), .Label = c("25-34", "35-44", "45-54", "55-64", 
    "65+"), class = "factor"), value = c(0.0035, 0.0058, 0.0089, 0, 0.00512820512820513, 
    0.00512820512820513)), .Names = c("Speciality", "PhysAge", "value"
    ), row.names = 155:160, class = "data.frame")

如何根据堆积条形图中每个Speciality的值总和在ggplot中重新排序。我找到了一些值为多列的选项,但在这种情况下,它是一个值列。

目前正在绘制: ggplot(df,aes(x=Speciality,y=value,fill=PhysAge))+ geom_bar(stat="identity")

1 个答案:

答案 0 :(得分:3)

你可以尝试

set.seed(1)
df <- rbind(
  AgevsPractice.melt, 
  transform(AgevsPractice.melt, PhysAge="1", value=runif(6, 0, 0.01)),
  transform(AgevsPractice.melt, PhysAge="10", value=runif(6, 0, 0.01))
)
ggplot(df,aes(x=reorder(Speciality, value, sum), y=value,fill=PhysAge))+
 geom_bar(stat="identity")