创建条形图ggplot2单个暗淡的数据帧

时间:2017-12-07 20:36:30

标签: r

我试图在ggplot2中创建一个条形图,我有一个包含列名和关联数值的数据框,但是我一直遇到创建数据帧的意外错误:

ggplot(audit_count,aes(x=colnames(audit_count),y=audit_count[1,])) +geom_bar()

给我错误信息

Error: Aesthetics must be either length 1 or the same as the data (1): x, y

但是这个错误信息对我来说没有意义,因为colnames(audit_count)和audit_count [1,]的长度相同。

我需要对我的数据进行某种转换才能将其绘制为条形图,列名称为条形名称,数值为y值吗?

以下数据:

structure(list(page_title_missing = 56L, page_title_length = 164L, 
    page_title_duplicates = 630L, meta_desc_missing = 703L, meta_desc_length = 0L, 
    meta_desc_duplicate = 28L, url_dynamic = 397L, url_underscore = 26L, 
    url_uppercase = 701L, pagination = 0L, image_alt_missing = 223L, 
    h1_missing = 56L, h1_multiple = 427L, meta_keyword_present = 0L, 
    https_missing = 0L, non_canonical = 293L, meta_no_index = 0L, 
    meta_no_follow = 0L, content_duplication = 617L, content_depth = 461L, 
    non_301_redirects = 55L, redirec_chains = 56L, errors_404 = 0L, 
    mobile_url_inconsisten = 0L, hreflang_missing = 731L), .Names = c("page_title_missing", 
"page_title_length", "page_title_duplicates", "meta_desc_missing", 
"meta_desc_length", "meta_desc_duplicate", "url_dynamic", "url_underscore", 
"url_uppercase", "pagination", "image_alt_missing", "h1_missing", 
"h1_multiple", "meta_keyword_present", "https_missing", "non_canonical", 
"meta_no_index", "meta_no_follow", "content_duplication", "content_depth", 
"non_301_redirects", "redirec_chains", "errors_404", "mobile_url_inconsisten", 
"hreflang_missing"), row.names = c(NA, -1L), class = "data.frame")

2 个答案:

答案 0 :(得分:0)

我会使用t()转置数据,然后将rownames()作为x并将V1作为y输入ggplot。在geom_bar()中,stat = 'identity'表示将值用作条形长度

library(ggplot2)
library(dplyr)

audit_count <- t(audit_count) %>% as.data.frame
ggplot(audit_count, aes(x = rownames(audit_count), y = V1)) + geom_bar(stat = 'identity') + coord_flip()

答案 1 :(得分:0)

ggplot期望数据格式整洁,aes()应将data.frame的列映射到图形属性。您并不是真的想将数据直接传递给aes。一个快速解决方法是

ggplot(tidyr::gather(audit_count, variable, value)) + 
    geom_bar(aes(x=variable,y=value), stat="identity") +
    coord_flip() 

ggplot(reshape2::melt(audit_count)) + 
    geom_bar(aes(x=variable,y=value), stat="identity") +
    coord_flip()