使用R中的Highcharter为每个条形图添加水平线。

huangapple go评论102阅读模式
英文:

Addings horizontals line on each Bar using Highcarter in R

问题

这是我的代码:

data <- gapminder::gapminder %>% filter(country == 'Brazil') %>%
  mutate(life = rnorm(12,mean = 55,sd = 5),
         months = month.abb)   

这是我的图表:

data %>%
      mutate(months = as_factor(months)) %>%
      mutate(index = rep(c(1,2),6), .before = everything()) %>%
      hchart(
        'column',
        names = 'SQUADS',
        hcaes(x = months,
              y = lifeExp,
              group = months),
        color = rep(c('#1B3D59','lightgray'),6),
        name = 'Sales',
        # groupPadding = 1.5,
        pointWidth = 20,
        showInLegend = FALSE
      )

我想要在表示life列值的每个柱形上添加水平线"--"以实现这个效果。

英文:

This is my code:

data <- gapminder::gapminder %>% filter(country == 'Brazil') %>%
  mutate(life = rnorm(12,mean = 55,sd = 5),
         months = month.abb)   

This is my chart:

 data%>%
      mutate(months = as_factor(months)) %>%
      mutate(index = rep(c(1,2),6), .before = everything()) %>%

      hchart(
        'column',
        names = 'SQUADS',
        hcaes(x = months,
              y = lifeExp,
              group = months),

        color = rep(c('#1B3D59','lightgray'),6),

        name = 'Sales',
        # groupPadding = 1.5,
        pointWidth = 20,
        showInLegend = FALSE
      )

I would like to add horizontal lines "--" on each bar that represents the values of life column to achieve this:

使用R中的Highcharter为每个条形图添加水平线。

答案1

得分: 2

我认为最简单的方法是使用 errorbars 来实现这个目标。基本上,你将使低值和高值相同,从而创建线段。

我在你的代码中添加了一个参数用于 column 图表。你需要使用 centerInCategory,否则柱形图将不会与误差线对齐。除了这个额外的参数之外,你的原始代码与你的问题中的代码相同。

在编写新系列时,我使用 life 作为线的位置。另外,你添加到 column 的任何间距规格也必须添加到 errorbar 中。

如果你有任何问题,请告诉我。

library(highcharter)
library(tidyverse)

data <- gapminder::gapminder %>%
  filter(country == 'Brazil') %>%
  mutate(life = rnorm(12, mean = 55, sd = 5),
         months = month.abb)

data %>%
  mutate(months = as_factor(months)) %>%
  mutate(index = rep(c(1,2), 6), .before = everything()) %>%
  
  hchart('column',
         names = 'SQUADS', name = 'Sales', 
         hcaes(x = months, y = lifeExp, group = months),
         color = rep(c('#1B3D59','lightgray'), 6),
         pointWidth = 20, showInLegend = FALSE,
         centerInCategory = T) %>%                   # <--- 我添加了这个!
  hc_add_series(data, "errorbar",
                hcaes(x = months, y = life, low = life, high = life, 
                      group = months),
                pointWidth = 20, whiskerLength = 20, # widths set match column
                centerInCategory = T, showInLegend = F)

使用R中的Highcharter为每个条形图添加水平线。


<details>
<summary>英文:</summary>

I think the easiest way to do this is with `errorbars`. Essentially, you&#39;ll make the low and high the same value, thus creating segments. 

I&#39;ve added one argument to your code for the `column` chart. You need `centerInCategory` otherwise the bars won&#39;t align with the error bars. Other than this one additional argument, your original code is the same as in your question.

When coding the new series, I used `life` as the position for the lines. Additionally, any specifications for spacing you add to the `column` you have to add to the `errorbar`, as well.

If you have any questions, let me know.
 

library(highcharter)
library(tidyverse)

data <- gapminder::gapminder %>% filter(country == 'Brazil') %>%
mutate(life = rnorm(12, mean = 55,sd = 5),
months = month.abb)

data %>%
mutate(months = as_factor(months)) %>%
mutate(index = rep(c(1,2), 6), .before = everything()) %>%

hchart('column',
names = 'SQUADS', name = 'Sales',
hcaes(x = months, y = lifeExp, group = months),
color = rep(c('#1B3D59','lightgray'), 6),
pointWidth = 20, showInLegend = FALSE,
centerInCategory = T) %>% # <--- I added this!
hc_add_series(data, "errorbar",
hcaes(x = months, y = life, low = life, high = life,
group = months),
pointWidth = 20, whiskerLength = 20, # widths set match column
centerInCategory = T, showInLegend = F)

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/LIcRX.png

</details>



# 答案2
**得分**: 1

@Kat的解决方案在所有方面都简单得多,可能是前进的方式。

以下是我尝试的方式,我认为它提供了更多的灵活性。我设置了一个自定义符号,用于标记。然后添加了一个线系列,`lineWidth = 0`,所以只显示标记。用这种方式做更容易与工具提示一起使用。此外,为了居中列,您可以使用`groupPadding = .5`。在JS加载函数中,我需要在图表渲染后手动更新符号。

如果您有任何问题,请告诉我!

```R
library(highcharter)
library(dplyr)

data = data %>%
  mutate(months = as.factor(months)) %>%
  mutate(index = rep(c(1,2),6), .before = everything())

highchart(type = "chart") %>%
  hc_xAxis(type = "categories", categories = unique(data2$months)) %>%
  hc_add_series(data, hcaes(x = months, y = lifeExp), type = "column", name = 'Sales',
    groupPadding = .5, 
    pointWidth = 20, 
    showInLegend = FALSE
  ) %>%
  hc_add_series(data, hcaes(x = months, y = life), type = "line", name = "Life",
    lineWidth = 0, states = list(hover = list(lineWidthPlus = 0)),
    showInLegend = FALSE
  ) %>%
  hc_plotOptions(
    line = list(
      marker = list(
        symbol = 'line', 
        lineWidth = 3,
        radius = 12, 
        lineColor = "#000")
      ),
    column = list(
      colorByPoint = TRUE,
      colors = rep(c("#4f8ec2",'lightgray'), 6) 
    )
    ) %>%
  hc_chart(
    events = list(
      load = JS("function(){
        Highcharts.SVGRenderer.prototype.symbols.line = function(x, y, w, h) {
                  return ['M',x ,y + w / 2,'L',x+h,y + w / 2];
        };
        this.series[1].update({marker: {symbol: 'line'}})
      }")
    )
  )

使用R中的Highcharter为每个条形图添加水平线。


<details>
<summary>英文:</summary>

@Kat &#39;s solution is on all accounts much simpler and probably the way to go. 

Below is my attempt which I believe offers more flexibility. I&#39;ve set up a custom symbol that&#39;s used for the marker. Then added a line series with `lineWidth = 0` so only the marker is shown. Doing it this way plays more nicely with the tooltip. Also to center the columns you can use `groupPadding = .5`. In the JS loading function - I needed to manually update the symbol once the chart has rendered.

Let me know if you have any questions!

library(highcharter)
library(dplyr)

data = data %>%
mutate(months = as.factor(months)) %>%
mutate(index = rep(c(1,2),6), .before = everything())

highchart(type = "chart") %>%
hc_xAxis(type = "categories", categories = unique(data2$months)) %>%
hc_add_series(data, hcaes(x = months, y = lifeExp), type = "column", name = 'Sales',
groupPadding = .5,
pointWidth = 20,
showInLegend = FALSE
) %>%
hc_add_series(data, hcaes(x = months, y = life), type = "line", name = "Life",
lineWidth = 0, states = list(hover = list(lineWidthPlus = 0)),
showInLegend = FALSE
) %>%
hc_plotOptions(
line = list(
marker = list(
symbol = 'line',
lineWidth = 3,
radius = 12,
lineColor = "#000")
),
column = list(
colorByPoint = TRUE,
colors = rep(c("#4f8ec2",'lightgray'), 6)
)
) %>%
hc_chart(
events = list(
load = JS("function(){
Highcharts.SVGRenderer.prototype.symbols.line = function(x, y, w, h) {
return ['M',x ,y + w / 2,'L',x+h,y + w / 2];
};
this.series1.update({marker: {symbol: 'line'}})
}")
)
)


[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/aw9D7.png

</details>



huangapple
  • 本文由 发表于 2023年6月8日 23:24:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定