在ggplot2中绘制具有离散轴的矩形和线范围

时间:2019-02-02 17:13:58

标签: r ggplot2 rectangles facet axis-labels

我对stackoverflow还是很陌生。 我想绘制矩形而不是线距,因为我想要黑色边框。实际上,我的教授想要一个黑色边框,但这不是stackoverflow的问题。

加载库并创建虚拟数据集

callback

如果仅使用线距进行绘制,则可以正常工作(目前还不允许嵌入图像)

               [&,callback /*pass by value*/](std::error_code ec, std::size_t size) 
              {
                 if (!ec) 
                 {
                   const auto available = m_socket->available();
                   m_buffer.resize(available);
                   m_buffer.shrink_to_fit();
                   asio::async_read(*m_socket, asio::buffer(m_buffer), asio::transfer_all());
                 }
                 callback(ec, std::move(m_buffer));
               });

仅用矩形绘制的图,失败,带有 错误:离散值提供给连续刻度

library(tidyverse)

mydat <- tibble(
       mymsmt = rep(c("bio", "bio", "den", "den"), 2),
       mylvl = c("NT", "till", "NT", "till", "no", "yes", "no", "yes"),
       mytrt = c(rep("tillage", 4), rep("herbicides", 4)),
       est = c(-60, -13, -65, -40, -16, -24, -49, -50),
       cilow = c(-85, -48, -78, -56, -61, -60, -68, -64),
       ciup = c(8, 45, -44, -18, 79, 42, -20, -31)) %>%
       # Dummy code mylvls as numeric
       mutate(mylvln = rep(c(1, 2), 4))  

具有线范围的图,被矩形覆盖, 您可以在后台看到线距

ggplot(mydat, aes(est, mylvl)) + 
  geom_linerangeh(aes(xmin = cilow, xmax = ciup), color = "blue", size = 5) +
  # geom_rect(aes(xmin = cilow, xmax = ciup, 
  #               ymin = mylvln - 0.2, ymax = mylvln + 0.2), 
  #           fill = "red", color = "black") +
  geom_point() + 
  facet_grid(mytrt ~ mymsmt, scales = "free")

为什么?它起作用了,我得到了想要的身材,但我不知道为什么。感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您也可以使用geom_tile代替geom_rect

ggplot(mydat, aes(est, mylvl)) + 
  geom_tile(aes(width = ciup-cilow, height=0.1),  fill="red", color="black") +
  geom_point() + 
  facet_grid(mytrt ~ mymsmt, scales = "free")

enter image description here