简体   繁体   English

带图例的条形图R中的列

[英]barplot with legend a columns in R

I'm trying to plot a bar plot of a data frame with n columns and m rows. 我正在尝试绘制具有n列和m行的数据框的条形图。 One of the rows houses the category, and I would like the barplot colors to be based on which category the column belongs to. 其中一行包含类别,我希望条形图颜色基于该列所属的类别。

Example : 范例:

example = as.data.frame(matrix(1:100, nrow = 1, ncol = 5),
                    dimnames(list(NULL, paste0('ColumnName_', 1:5)))) 
category = as.data.frame(matrix(c('cat.1', 'cat.1', 'cat.2', 'cat.4', 'cat.3'),
                            nrow = 1, ncol = 5), 
                     dimnames(list(NULL, paste0('ColumnName_', 1:5)))) 
example_df = rbind(example, category)
rownames(example_df) <- c('values 1', 'categories')

I'd like a barplot with the column names on the x axis, the and the values 1 row as data, but collored with respect to the category row. 我想要一个带有x轴上的列名,1和值1行作为数据的小节图,但相对于类别行来说却很合适。

Thank you. 谢谢。

Try something like this. 尝试这样的事情。 Note how the data is structured to work well with ggplot. 注意数据的结构如何与ggplot配合使用。

library(ggplot)
data <- data.frame(animal = c("Cat", "Dog", "Shark", "Fish"), 
                   home = c("land", "land", "sea", "sea"), 
                   age = c(2,7,9,5))

ggplot(data, aes(x = animal, y = age, fill = home)) + 
    geom_bar(stat = "identity")

在此处输入图片说明

Ok, using your code, and restructuring into tidy format: 好的,使用您的代码,并将其重组为整齐的格式:

example = as.data.frame(matrix(1:100, nrow = 1, ncol = 5),
                        dimnames(list(NULL, paste0('ColumnName_', 1:5)))) 
category = as.data.frame(matrix(c('cat.1', 'cat.1', 'cat.2', 'cat.4', 'cat.3'),
                                nrow = 1, ncol = 5), 
                         dimnames(list(NULL, paste0('ColumnName_', 1:5)))) 

example_df = rbind(example, category)
rownames(example_df) <- c('values 1', 'categories')

example_df <- as.data.frame(t(example_df))
example_df["names"] <- rownames(example_df)
ggplot(example_df, aes(x = names, y = `values 1`, fill = categories)) + geom_bar(stat = "identity")

在此处输入图片说明

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM