使用ggplot2并排绘制条形图中的两个变量

时间:2017-10-04 13:00:28

标签: r ggplot2

我想我需要使用融合功能,但我不知道该怎么做?下面的示例数据,代码和结果图。基本上,“cnt”列由每行的“已注册”和“随意”组成。我希望每月显示总“已注册”与总“休闲”,而不是总计“cnt”

example data

 public class TestBigDecimalOutput {
        public static void main(String[] args) {

            BigDecimal d = new BigDecimal("57657657657453646587980887663654676580.24545346565476767645");
            String outPlainString = d.toPlainString();
            String outEngineeringString = d.toEngineeringString();
            String outString = d.toString();

            System.out.println(outPlainString);
            System.out.println(outEngineeringString);
            System.out.println(outString);
        }
    }

enter image description here

2 个答案:

答案 0 :(得分:0)

使用reshape2::melt

“融化”您的数据
library(ggplot2)
library(reshape2)

# Subset your data
d <- subset(bikesharedailydata, !is.na(mnth))
# Select columns that you will plot
d <- d[, c("mnth", "registered", "casual")]
# Melt according to month
d <- melt(d, "mnth")

# Set fill by variable (registered or casual)
ggplot(d, aes(mnth, value, fill = variable)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    coord_flip() + 
    labs(title="My Bar Chart", subtitle = "Total Renters per Month", 
         caption = "Caption", 
         x = "Month", y = "Total Renters")

答案 1 :(得分:0)

使用tidyr和dplyr:

set.seed(1000)
library(dplyr)
library(tidyr)
library(ggplot2)

bikesharedailydata <- data.frame(month = month.abb, registered = rpois(n = 12, lambda = 2), casual =rpois(12, lambda = 1))


bikesharedailydata %>% gather(key="type", value = "count", -month) %>%
  ggplot(aes(x=month, y=count, fill = type))+geom_bar(stat = "identity", position = "dodge")

enter image description here