ggplot2:重叠元素

时间:2017-01-14 22:49:15

标签: r ggplot2

我有一些关于每个月每月的低和高平均温度的数据。我把它们放在条形图中,温度越高温度越高,看看差异。但我想只有差异,所以重叠(和图中的蓝色)是空白的。有没有办法如何处理ggplot中的重叠元素?

dat <- data.frame(1:12, 1:12, 1:12)
colnames(dat) <- c("Th", "Tl")
dat$code <- c("Jan",    "Feb",  "Mar",  "Apr",  "May",  "Jun",  "Jul",  "Aug",  "Sep",  "Oct",  "Nov",  "Dec")
dat$code <- factor(dat$code, levels = dat$code)
dat$Th <- c(42, 44, 53, 64, 75, 83, 87, 84, 78, 67, 55, 45)
dat$Tl <- c(27, 28, 35, 44, 54, 63, 68, 66, 59, 48, 38, 29)
dat

p <- ggplot(data = dat, aes(x = clim$code, y = Th)) +
      geom_col(show.legend = FALSE) +
      geom_bar(data = dat, aes(x = clim$code, y = Tl), fill = "blue", stat="identity")
p

plot

1 个答案:

答案 0 :(得分:4)

您可以使用geom_segment近似条形图:

ggplot(dat, aes(x = code, xend = code, y = Th, yend = Tl)) + 
    geom_segment(size = 14, alpha = 0.7)

segment plot

y轴不再默认为零,但如果你想要它(温度可能不需要),你可以添加expand_limits(y = 0)

如果你想实际使用geom_bar,你可以调整你的数据,这样你就可以在一次调用中制作两组条形图,然后将堆栈中较低的条形图的填充设置为RGB值。 00作为额外的alpha(不透明度)值。但是,它有点复杂:

library(tidyverse)

dat[-3] %>%    # calling a column `NA` causes problems
    mutate(Th = Th - Tl) %>%    # adjust top of stacked highs
    gather(var, val, Th, Tl) %>%    # reshape to long form
    ggplot(aes(x = code, y = val, fill = var)) + 
    geom_bar(stat = 'identity', show.legend = FALSE) + 
    scale_fill_manual(values = c(Th = 'gray30', Tl = '#00000000'))    # set fills/opacity

barplot

另外,因为每个人都在geom_bar使用stat = "identity"这么多,所以添加了geom_col stat = "identity"作为默认值(h / t @hrbrmstr!),如果你的ggplot是最新的,你可以弹出geom_col(show.legend = FALSE)以上的const http = require('http'); const hostname = '192.168.1.116'; const portserver = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); var SerialPort = require("serialport"); var serialPort = new SerialPort('COM2', {baudrate: 9600}); serialPort.on ('open', function () { console.log("Open"); serialPort.write(0x05); }); res.end('Hello') }); server.listen(portserver, hostname, () => { console.log(`Server running at http://${hostname}:${portserver}/`); });