本文介绍了按降序显示数据,如数据框中所示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我一直在争取在ggplot2中作为条形图进行排序并绘制一个简单的数据框。 我想绘制出现的数据,以便相应类别(例如'人类','男性')的值('count'变量)是从高到低绘制。 ##数据集( mesh2) #Category Count #人62 #男40 #女38 #Adult 37 #中老年30 #肝脏/解剖结构&组织学29 #组织学大小29 #青少年28 #儿童21 #肝脏/放射线摄影* 20 #肝移植* 20 #Tomography,X-Ray计算20 #体重18 # Child,Preschool 18 #活体捐赠者* 18 #Infant 16 #Aged 14 #Body Surface区域14 #回归分析11 #肝切除术10 ##读取数据(mesh2)作为对象(mesh2) mesh2< - read.csv(mesh2.csv,header = T) ##通过网格变量计数的顺序数据 mesh2 $ cat2 < - order(mesh2 $ Category,mesh2 $ Count,decrease = TRUE) ##在ggplot2中创建的Barplot 库(ggplot2) mesh2p 解决方案您需要 reorder(),下面是一个虚拟数据示例 pre $ set.seed(42) df require(ggplot2) p1 geom_bar(stat =identity ) p2 geom_bar(stat =identity) require(gridExtra) grid.arrange(arrangeGrob(p1,p2)) 给予: 使用重新排序(类别,计数)使 Category 从低到高排序。 I've been battling to order and plot a simple dataframe as a bar chart in ggplot2. I want to plot the data as it appears, so that the values ('count' variable) for the corresponding categories (e.g. 'humans', 'male') are plotted from high to low. I've followed other threads on this site asking similar questions, but can't get this to work!## Dataset (mesh2)#Category Count#Humans 62#Male 40#Female 38#Adult 37#Middle Aged 30#Liver/anatomy & histology 29#Organ Size 29#Adolescent 28#Child 21#Liver/radiography* 20#Liver Transplantation* 20#Tomography, X-Ray Computed 20#Body Weight 18#Child, Preschool 18#Living Donors* 18#Infant 16#Aged 14#Body Surface Area 14#Regression Analysis 11#Hepatectomy 10## read in data (mesh2) as object (mesh2)mesh2 <- read.csv("mesh2.csv", header = T)## order data by count of mesh variablemesh2$cat2 <- order(mesh2$Category, mesh2$Count, decreasing=TRUE)## Barplot created in ggplot2library(ggplot2)mesh2p <- ggplot(mesh2, aes(x=cat2, y=Count)) + geom_bar (stat="identity") + scale_x_continuous(breaks=c(1:20), labels=c("Humans", "Male", "Female", "Adult", "MAged", "Liver anat & hist", "Organ Size", "Adolescent", "Child", "Liver radiog", "Liver Transplnt", "Tomog X-Ray Computed", "Body Weight", "Child Preschool", "Living Donors", "Infant", "Aged", "BSA", "Regression Analysis", "Hepatectomy"))+ theme (axis.text.x=element_text(angle=45, hjust=1))Apparently I can't post output as I don't have enough 'reputation'? 解决方案 You want reorder(). Here is an example with dummy dataset.seed(42)df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))require("ggplot2")p1 <- ggplot(df, aes(x = Category, y = Count)) + geom_bar(stat = "identity")p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) + geom_bar(stat = "identity")require("gridExtra")grid.arrange(arrangeGrob(p1, p2))Giving:Use reorder(Category, Count) to have Category ordered from low-high. 这篇关于按降序显示数据,如数据框中所示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-14 04:00