简体   繁体   English

如何使用一维数据框在ggplot aes中设置x,y?

[英]How to set x,y in ggplot aes with one dimension dataframe?

df <- data.frame(
    cola = c('1',NA,'c','1','1','e','1',NA,'c','d'),
    colb = c("A",NA,"C","D",'a','b','c','d','c','d'),
    colc = c('a',NA,'c','d','a',NA,'c',NA,'c','d'),stringsAsFactors = TRUE)

bad<-lapply(df, function(x) sum(is.na(x))/nrow(df))
bad<-as.data.frame(bad)

I want to make bar plot to one dimension dataframe bad . 我想使对一维数据框的条形图bad

X axis should be cola , colb , colc ,Y axis should be 0.2 , 0.1 , 0.3 . X轴应该是colacolbcolc ,Y轴应该是0.20.10.3 Then I tried but failed: 然后我尝试但失败了:

ggplot(bad,aes(x=colnames(bad), y=bad[1,])) + 
    geom_bar(stat='identity')

As to one dimension dataframe,how to set aes(x=?,y=?) ? 对于一维数据帧,如何设置aes(x=?,y=?)

You need to convert your data frame to long format. 您需要将数据帧转换为长格式。 You can use reshape2's melt function. 您可以使用reshape2的melt函数。

dab <- reshape2::melt(bad)

> dab
  variable value
1     cola   0.2
2     colb   0.1
3     colc   0.3

ggplot(dab) + geom_bar(aes(x=variable, y=value, fill=variable), stat='identity')

You need to change the dimension of the dataframe 您需要更改数据框的尺寸

library(ggplot2)
ggplot(stack(bad), aes(ind, values)) + geom_bar(stat='identity')

在此处输入图片说明

Or if you want to go the tidyverse way we can use gather as well 或者,如果你想要去的tidyverse方式,我们可以使用gather以及

ggplot(tidyr::gather(bad), aes(key, value)) + geom_bar(stat='identity')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在循环中使用 ggplot2 来绘制来自一个 dataframe 的 x 值和来自另一个的 y - How to use ggplot2 inside a loop for plotting x values from one dataframe and y from other 如何查看分配给值的原始代码,例如[x &lt; - ggplot(ToothGrowth,aes(x = dose,y = len,color = dose))] - How to see the original code assigned to a value, such as [x <- ggplot(ToothGrowth, aes(x=dose, y=len, color=dose))] 如何在ggplot2中设置y =行和x =列? - How to set y=rows and x=columns in ggplot2? 如何在ggplot分组条形图上设置x-y轴? - How to set x - y axis on ggplot grouped bar chart? 如何使用一个“x”值和多个“y”值制作ggplot - How to make a ggplot with one 'x' value and multiple 'y' values 如何为ggplot的aes使用数据框的名称和rownames? - How to use names and rownames of a dataframe for the aes of ggplot? 如何在一幅图中绘制lm(log(y)〜)和lm(y〜x + x ^ 2)的ggplot - How to draw ggplot of lm(log(y)~)and lm(y~x+x^2) in one plot 关于ggplot2中的geom_segment(aes(x = x0,y = y0,xend = x1,yend = y1)) - regarding geom_segment(aes(x=x0,y=y0,xend=x1,yend=y1)) in ggplot2 如何将变量传递到函数的ggplot aes / ..y ..部分 - How to pass variable into ggplot aes / ..y.. part of function 如何在ggplot中用相同的x绘制不同的y? - How to plot different y with the same x in ggplot?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM