仅在图例中显示绘制的数据 [英] display only plotted data in the legend

查看:92
本文介绍了仅在图例中显示绘制的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

library(ggplot2)
df = data.frame(x = 1:5, y = 1:5, z = c('a', 'a', 'a', 'b', 'b'))

ggplot(df, aes(x, y, col = z)) + geom_line() + geom_point() +
  coord_cartesian(xlim = c(1, 2.5))

仅显示a存储桶中的数据,但ab都出现在图例中.如何解决这个问题,以便图例中仅显示实际绘制的存储桶?

Only data from the a bucket is displayed, yet both a, and b appear in the legend. How can I fix this, so that only the bucket that is actually plotted appears in the legend?

就上下文而言-我在尝试放大视图时遇到了这个问题shiny中.

For context - I'm encountering this while trying zooming into plots in shiny.

推荐答案

z上进行过滤是否可以覆盖您的实际用例?例如:

Does filtering on z cover your actual use case? For example:

library(tidyverse)

df = data.frame(x = 1:5, y = 1:5, z = c('a', 'a', 'a', 'b', 'b'))

ggplot(df %>% filter(z %in% z[between(x,1,2.5)]), 
       aes(x, y, col = z)) + 
  geom_line() + geom_point() +
  coord_cartesian(xlim = c(1, 2.5))

或在可以针对用户输入的美学变量进一步推广的功能中. (我还更新了该功能,即使在不包含数据点的绘图区域中也可以使用插值来绘制线,只要点之间的至少一条连接线穿过绘图区域即可.)

Or in a function that could be further generalized for user-entered aesthetic variables. (I've also updated the function to use interpolation to plot lines even in plot regions that contain no data points, so long as at least one connecting line between points passes through the plot region.)

my_plot = function(xrng, data=df, step=0.01) {

  levs = unique(data[["z"]])  
  n = length(levs)

  # Generate interpolated data frame so we can plot lines even if 
  # no points appear in the graph region 
  dat_interp = split(data, data$z) %>% 
    map_df(function(d) {
      x = seq(min(d$x), max(d$x), step)
      data.frame(z=rep(unique(d$z), each=length(x)),
                 x, y=rep(approx(d$x, d$y, xout=x)$y, n))
    })

  ggplot(dat_interp %>% filter(z %in% z[between(x,xrng[1],xrng[2])]), 
         aes(x, y, col = z)) + 
    geom_point(data=data %>% filter(z %in% z[between(x,xrng[1],xrng[2])])) +
    geom_line() + 
    coord_cartesian(xlim = xrng) +
    scale_color_manual(values=setNames(hcl(seq(15,375,length=n+1)[1:n],100,65), levs))
}


gridExtra::grid.arrange(
  my_plot(c(1,2.5)),
  my_plot(c(1,4)),
  my_plot(c(3,4)),
  my_plot(c(4.3,6)),
  my_plot(c(1.1,1.6)),
  my_plot(c(4.2,4.9)))

这篇关于仅在图例中显示绘制的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆