R - 使用ggplot2对函数中的条形图重新排序

时间:2016-11-09 16:28:15

标签: r plot ggplot2

我使用ggplot2创建了以下绘图函数。

Function_Plot <- function(Fun_Data, Fun_Color)
{
  MyPlot <- ggplot(data = na.omit(Fun_Data), aes_string(x = colnames(Fun_Data[2]), fill = colnames(Fun_Data[1]))) +
            geom_bar(stat = "count") +
            coord_flip() +
            scale_fill_manual(values = Fun_Color)
  return(MyPlot)
}

结果是:

Image

我需要升级我的功能,根据单词的频率重新排序吧(按降序排列)。当我看到关于重新排序的另一个问题的答案时,我尝试在reorder中引入aes_string函数,但它不起作用。

可重现的例子:

a <- c("G1","G1","G1","G1","G1","G1","G1","G1","G1","G1","G2","G2","G2","G2","G2","G2","G2","G2")
b <- c("happy","sad","happy","bravery","bravery","God","sad","happy","freedom","happy","freedom",
       "God","sad","happy","freedom",NA,"money","sad")

MyData <- data.frame(Cluster = a, Word = b)
MyColor <- c("red","blue")

Function_Plot(Fun_Data = MyData, Fun_Color = MyColor)

1 个答案:

答案 0 :(得分:1)

好吧,如果重新排序在 aes_string无效,请让我们事先尝试。

Function_Plot <- function(Fun_Data, Fun_Color)
{
  Fun_Data[[2]] <- reorder(Fun_Data[[2]], Fun_Data[[2]], length)
  MyPlot <- ggplot(data = na.omit(Fun_Data), aes_string(x = colnames(Fun_Data[2]), fill = colnames(Fun_Data[1]))) +
            geom_bar(stat = "count") +
            coord_flip() +
            scale_fill_manual(values = Fun_Color)
  return(MyPlot)
}

Function_Plot()

enter image description here

结合其他笔记 - 我建议你使用更一致的风格,混合是否使用_来分隔变量名中的单词会让人感到困惑并要求提供错误。

除非您的数据真的大,否则它不会有什么关系,但从数据帧中提取名称非常有效,而对数据帧进行子集化则效率较低。您的代码将数据框设置为子集,然后提取剩余的列名称,例如colnames(Fun_Data[1])。提取名称然后对该向量进行子集化将更加清晰:colnames(Fun_Data)[1]