Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 根据ggplot中的变量重新排列x轴_R_Ggplot2 - Fatal编程技术网

R 根据ggplot中的变量重新排列x轴

R 根据ggplot中的变量重新排列x轴,r,ggplot2,R,Ggplot2,我正试图用ggplot对数据帧plot\u data进行条形图绘制。在x轴上,我希望由Duree\u moy\u trans(行程持续时间)订购Destination,标签形式为“持续时间(Duree\u moy\u trans)”。y轴应为值,条形图应按分类着色 我曾尝试使用reorder()对x轴进行排序,并使用scale\u x\u discrete()设置标签,但未能获得所需的结果。我怎么画这个图 这是我迄今为止尝试过的数据和代码: plot_data= structure(list(D

我正试图用ggplot对数据帧
plot\u data
进行条形图绘制。在x轴上,我希望由
Duree\u moy\u trans
(行程持续时间)订购
Destination
,标签形式为“
持续时间(Duree\u moy\u trans)
”。y轴应为
,条形图应按
分类
着色

我曾尝试使用
reorder()
对x轴进行排序,并使用
scale\u x\u discrete()
设置标签,但未能获得所需的结果。我怎么画这个图

这是我迄今为止尝试过的数据和代码:

plot_data= structure(list(Destination = structure(c(1L, 2L, 6L, 8L, 11L, 
12L), .Label = c("ABL", "ARP", "ATH", 
"BIE", "BOU", "BRE", "BRU", "BRI", 
"CHA", "CHE", "CHI", "CHO", 
"DOU", "EGL", "EPI", "ETA", "ETR", "GRA", 
"IVR", "JUV", "LAN", 
"LAR", "LES", "LEA", "LON", "MARO", 
"MAS", "MAS", "ORL", "PET", 
"PON", "RUN", "SAI", 
"SAM", "SAG", "SAV", 
"SER", "VER", "VIL", "VIT"
), class = "factor"), Duree_moy_trans = c(15L, 36L, 28L, 44L, 
32L, 9L), Categorie = c("3", "3", "3", "3", "3", "3"), value = c(1, 
3, 2, 3, 1.33333333333333, 4)), .Names = c("Destination", "Duree_moy_trans", 
"Categorie", "value"), row.names = c(NA, 6L), class = "data.frame")


library(ggplot2)
ggplot(plot_data, aes(reorder(Duree_moy_trans, -value), y = value,
       group= Categorie, fill = Categorie)) + 
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "Destination",
                   labels = paste(plot_data$Destination," ( ",plot_data$Duree_moy_trans," ) ",sep="")) + 
  theme(plot.title = element_text(size=16,lineheight=2, face="bold")) +   
  scale_y_continuous(name=" Pourcentage %",limits = c(0,25))  

从你的问题来看,我不确定所需的顺序是什么:你说你想通过
Duree\u moy\u trans
订购,但在
reorder()中使用
-value
。在下文中,我假设您希望通过
Duree\u moy\u trans
订购

为了获得所需的标签(
Destination(Duree\u moy\u trans)
),我认为在绘图之前在数据中设置标签比较容易。您可以同时对系数重新排序:

new_dest <- paste0(plot_data$Destination, " (", plot_data$Duree_moy_trans, ")")
plot_data$Destination <- reorder(new_dest, plot_data$Duree_moy_trans)


请注意,您不需要
group=Categorie

什么是
i
DF
?你的例子远非微不足道。删除不必要的内容,如标题和主题()
(当然,除非它们确实与您的问题相关)。请确保您的代码可以从干净的R会话中运行。对不起,现在我放置了可以在干净的R会话中运行的最小代码。谢谢更好,谢谢你!不客气!你介意我把你的问题改清楚一点吗?是的,你当然可以!
ggplot(plot_data, aes(x = Destination, y = value, fill = Categorie)) +
  geom_bar(stat = "identity") + 
  scale_y_continuous(name=" Pourcentage %",limits = c(0,25))