简体   繁体   English

如何使用ggplot2绘制分组条形图,分段条形图和脊柱图?

[英]How can I draw grouped bar charts, segmented bar plot and spine plot using ggplot2?

I'm trying to draw a grouped bar plot in r 我正在尝试在R中绘制分组的条形图

Here is my code: 这是我的代码:

xtable <- xtabs(~ view + grade, data=hs)

xtable

barplot(xtable, beside = T, legend.text = T)

library(reshape2)
data.m <- melt(xtable, id.vars='view')

data.m
# plot
ggplot(data.m, aes(grade, value)) + geom_bar(aes(fill = view), 
   width = 0.4, position = "dodge", stat="identity") +  
   theme(legend.position="top", legend.title = 
   element_blank(),axis.title.x=element_blank(), 
   axis.title.y=element_blank())

View and grade are two properties of homes sold. 视图和等级是所售房屋的两个属性。 Grade is a value between 0 to 13 showing the rank of a home, and view is 0 to 4 showing how good is the view of the home. 等级是介于0到13之间的值,表示房屋的等级,而视图是介于0到4之间的值,表示房屋的外观有多好。

The usual barplot command in r works oaky. R中通常的barplot命令工作于Oaky。 However, I liked a ggplot for it. 但是,我喜欢它的ggplot。 I followed the answer of similar questions, but I get a stacked bar instead of a grouped one. 我遵循了类似问题的答案,但是我得到了一个堆叠的条,而不是一个分组的条。 Also, how can I generate a segmented bar plot and spine plot using the same data? 另外,如何使用相同的数据生成分段条形图和脊柱图?

在此处输入图片说明

Your code considers view as continuous, where it is not. 您的代码认为view是连续的,而不是连续的。 Convert it to factor . 将其转换为factor

library(ggplot2)
library(reshape2)

hs <- read.csv(file = file.choose())

xtable <- xtabs(formula = (~ view + grade),
                data = hs)

data.m <- melt(data = xtable,
               id.vars='view')

ggplot(data = data.m,
       mapping = aes(x = grade,
                     y = value)) +
  geom_bar(mapping = aes(fill = factor(x = view)),
           position = "dodge",
           stat="identity")

This generates the following, which you can modify later to make it look nicer. 这将生成以下内容,您可以稍后对其进行修改以使其看起来更好。

side_by_side_barplot

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

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