【问题标题】:Add a horizontal discrete legend below the chart in ggvis在 ggvis 中的图表下方添加水平离散图例
【发布时间】:2016-09-24 17:16:37
【问题描述】:

我想在ggvis 图表下方制作一个水平图例。我可以使用图例属性将其放置在图表下方,但不知道如何使标签水平位于图例标题下方。下面是最小的可重现代码(从网上获取)。

df1 = data.frame(x=sample(1:10), y=sample(1:10))
df2 = data.frame(x=1:10, y=1:10)
df3 = data.frame(x=1:10, y=sqrt(1:10))

df2$id <- 1
df3$id <- 2
df4    <- rbind(df2,df3)
df4$id <- factor(df4$id)

df4 %>% ggvis(x=~x, y=~y, stroke=~id) %>% layer_lines() %>%
    # make sure you use add relative scales
    add_relative_scales() %>%
    # values for x and y need to be between 0 and 1
    # e.g for the x-axis 0 is the at far-most left point and 1 at the far-right 
    add_legend("stroke", title="Cylinders",
               properties=legend_props(
                   legend=list(
                       x=scaled_value("x_rel", 0.2),
                       y=scaled_value("y_rel", -.2)
                   ))) %>%
    layer_points(x=~x, y=~y, data=df1, stroke:='black') 

【问题讨论】:

  • 由于这似乎仍然是一个悬而未决的问题over at the ggvis GitHub developer page,我怀疑这在没有重大黑客攻击的情况下是可能的。但我可能是错的。
  • @Felix 知道 ggvis 是否已添加此功能?
  • 我的答案看起来像你要找的吗?

标签: r plot ggvis legend-properties


【解决方案1】:

这肯定是一个 hack,但效果很好:

df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>%
  #make sure you use add relative scales
  add_relative_scales() %>%
  #values for x and y need to be between 0 and 1
  #e.g for the x-axis 0 is the at far-most left point and 1 at the far-right 
  add_legend("stroke", title = "Cylinders", values = c(1, 1),
             properties = legend_props(
               legend = list(
                 x = scaled_value("x_rel", 0.2),
                 y = scaled_value("y_rel", -.2)
               ))) %>%
  add_legend("stroke", title = " ", values = c(2, 2),
             properties = legend_props(
               legend = list(
                 x = scaled_value("x_rel", 0.23),
                 y = scaled_value("y_rel", -.2)
               ))) %>%
  layer_points(x=~x,y=~y,data = df1,stroke:='black') 

基本上,我添加了另一个add_legend,将标题设置为空白,调整scale_value,使其非常接近第一个图例但不重叠。然后我用values = c(1,1) 设置第一个图例,用values = c(2,2) 设置第二个图例,这样两个值就可以堆叠在一起。这使它看起来像一个具有水平值的图例。

【讨论】:

    【解决方案2】:

    看到ggvis现在处于休眠状态,也许你可以考虑切换到googleVis

    这里是一个类似的图,你可以通过稍微操作你的样本数据来获得:

    df5 <- df4[df4$id==1,]
    colnames(df5)[2] <- "y1"
    
    library(tidyverse)
    
    df5 <- df5 %>%
      mutate(
        y0 = df1[order(df1$x),c(2)],
        y2 = sqrt(x)
      )
    
    df5 <- df5[, c(1,4,2,5)]
    
    library(googleVis)
    
    plot_df5 <- gvisLineChart(df5, options=list(
                                                legend="bottom",
                                                series =
                                                "[{labelInLegend: 'Dot', color: 'black'},                                            
                                                {labelInLegend: 'Cylinders: 1', color: 'blue', curveType: 'dot'},
                                                {labelInLegend: 'Cylinders: 2', color: 'orange'}]"
                                               )
                             )
    plot(plot_df5)
    

    <!-- LineChart generated in R 3.5.2 by googleVis 0.6.2 package -->
    <!-- Sun Dec 30 21:21:26 2018 -->
    
    
    <!-- jsHeader -->
    <script type="text/javascript">
    
    
    // jsData 
    function gvisDataLineChartID1fd8710660d () {
    var data = new google.visualization.DataTable();
    var datajson =
    [
     [
    "1",
    3,
    1,
    1
    ],
    [
    "2",
    4,
    2,
    1.414213562
    ],
    [
    "3",
    6,
    3,
    1.732050808
    ],
    [
    "4",
    1,
    4,
    2
    ],
    [
    "5",
    10,
    5,
    2.236067977
    ],
    [
    "6",
    8,
    6,
    2.449489743
    ],
    [
    "7",
    7,
    7,
    2.645751311
    ],
    [
    "8",
    2,
    8,
    2.828427125
    ],
    [
    "9",
    9,
    9,
    3
    ],
    [
    "10",
    5,
    10,
    3.16227766
    ] 
    ];
    data.addColumn('string','x');
    data.addColumn('number','y0');
    data.addColumn('number','y1');
    data.addColumn('number','y2');
    data.addRows(datajson);
    return(data);
    }
    
    
    // jsDrawChart
    function drawChartLineChartID1fd8710660d() {
    var data = gvisDataLineChartID1fd8710660d();
    var options = {};
    options["allowHtml"] = true;
    options["legend"] = "bottom";
    options["series"] = [{labelInLegend: 'Dot', color: 'black'},                                            
                                                {labelInLegend: 'Cylinders: 1', color: 'blue', curveType: 'dot'},
                                                {labelInLegend: 'Cylinders: 2', color: 'orange'}];
    
    
        var chart = new google.visualization.LineChart(
        document.getElementById('LineChartID1fd8710660d')
        );
        chart.draw(data,options);
        
    
    }
      
    
    
    // jsDisplayChart
    (function() {
    var pkgs = window.__gvisPackages = window.__gvisPackages || [];
    var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
    var chartid = "corechart";
      
    // Manually see if chartid is in pkgs (not all browsers support Array.indexOf)
    var i, newPackage = true;
    for (i = 0; newPackage && i < pkgs.length; i++) {
    if (pkgs[i] === chartid)
    newPackage = false;
    }
    if (newPackage)
      pkgs.push(chartid);
      
    // Add the drawChart function to the global list of callbacks
    callbacks.push(drawChartLineChartID1fd8710660d);
    })();
    function displayChartLineChartID1fd8710660d() {
      var pkgs = window.__gvisPackages = window.__gvisPackages || [];
      var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
      window.clearTimeout(window.__gvisLoad);
      // The timeout is set to 100 because otherwise the container div we are
      // targeting might not be part of the document yet
      window.__gvisLoad = setTimeout(function() {
      var pkgCount = pkgs.length;
      google.load("visualization", "1", { packages:pkgs, callback: function() {
      if (pkgCount != pkgs.length) {
      // Race condition where another setTimeout call snuck in after us; if
      // that call added a package, we must not shift its callback
      return;
    }
    while (callbacks.length > 0)
    callbacks.shift()();
    } });
    }, 100);
    }
    
    
    // jsFooter
    </script>
    
    
    <!-- jsChart -->  
    <script type="text/javascript" src="https://www.google.com/jsapi?callback=displayChartLineChartID1fd8710660d"></script>
    
    
    <!-- divChart -->
      
    <div id="LineChartID1fd8710660d" 
      style="width: 500; height: automatic;">
    </div>

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 2015-07-14
      • 2023-03-27
      • 1970-01-01
      • 2019-08-15
      • 2020-08-23
      • 2015-08-04
      • 1970-01-01
      相关资源
      最近更新 更多