如果我有以下情节,如何在绘图前禁止重新洗牌?我想在图中保持与我试图绘制的数据框中相同的数据顺序。非常感谢任何帮助
df <- data.frame(derma=c(1:14), prevalence=c(1:14))
df$derma = c("Spotted melanosis","Diffuse melanosis on palm","Spotted melanosis on trunk","Diffuse melanosis on trunk","Leuco melanosis","Whole body melanosis","Spotted keratosis on palm","Diffuse keratosis on palm","Spotted keratosis on sole","Diffuse keratosis on sole","Dorsal keratosis","Chronic bronchitis","Liver enlargement","Carcinoma")
df$prevalence = c(16.2,78.6,57.3,20.6,17,8.4,35.4,23.5,66,52.8,39,6,2.4,1)
g <- ggplot(data=df, aes(x=derma, y=prevalence)) + geom_bar(stat="identity") + coord_flip()
print(g)
答案 0 :(得分:0)
如评论中所述,您可以通过订购因子变量来完成此操作。以下是示例代码:
df <- data.frame(derma=c(1:14), prevalence=c(1:14))
df$derma = c("Spotted melanosis","Diffuse melanosis on palm","Spotted melanosis on trunk","Diffuse melanosis on trunk","Leuco melanosis","Whole body melanosis","Spotted keratosis on palm","Diffuse keratosis on palm","Spotted keratosis on sole","Diffuse keratosis on sole","Dorsal keratosis","Chronic bronchitis","Liver enlargement","Carcinoma")
df$prevalence = c(16.2,78.6,57.3,20.6,17,8.4,35.4,23.5,66,52.8,39,6,2.4,1)
df$derma <- factor(df$derma, levels = df$derma, ordered=TRUE)
g <- ggplot(data=df, aes(x=derma, y=prevalence)) + geom_bar(stat="identity") + coord_flip()
print(g)
您可以使用标签并在图中为其提供所需的顺序。例如,您可以通过简单地使用rev()
函数来反转绘图中的元素。以下是相同的代码:
df <- data.frame(derma=c(1:14), prevalence=c(1:14))
df$derma = c("Spotted melanosis","Diffuse melanosis on palm","Spotted melanosis on trunk","Diffuse melanosis on trunk","Leuco melanosis","Whole body melanosis","Spotted keratosis on palm","Diffuse keratosis on palm","Spotted keratosis on sole","Diffuse keratosis on sole","Dorsal keratosis","Chronic bronchitis","Liver enlargement","Carcinoma")
df$prevalence = c(16.2,78.6,57.3,20.6,17,8.4,35.4,23.5,66,52.8,39,6,2.4,1)
df$derma <- factor(df$derma, levels = rev(df$derma), ordered=TRUE)
g <- ggplot(data=df, aes(x=derma, y=prevalence)) + geom_bar(stat="identity") + coord_flip()
print(g)