【问题标题】:Create a dial plot in R using plotly or ggplot2使用 plotly 或 ggplot2 在 R 中创建拨号图
【发布时间】:2020-04-28 16:05:04
【问题描述】:

我想创建一个函数,它接受一些输入,并根据这些输入返回一个类似于下图所示的绘图对象:

两半在表盘位置和颜色上是镜像的,但中间的文字和标签不同。我看过一些例子,但它们并没有完全涵盖我需要的内容:

  1. ggplot Donut chart
  2. Dial Position Gauge Chart Plotly R,
  3. https://www.r-graph-gallery.com/doughnut-plot.html
  4. Hide labels in plotly donut chart r

示例代码

首先使用plotly 尝试绘图的上半部分:

plot_func <- function(current_value){
  fig <- plot_ly(
    domain = list(x = c(0, 1), y = c(0, 1)),
    value = current_value,
    title = list(text = "Rating"),
    type = "indicator",
    mode = "number+gauge",
    gauge = list(
      axis =list(range = list(100, 85)),
      bar = list(
        # color = 'white', 
        # line = list(width = 1), 
        thickness = 0
      ),
      steps = list(
        list(range = c(85,90), color = "#b20000", name = 'E'),
        list(range = c(90,92.5), color = "#e09999", name = 'D'),
        list(range = c(92.5, 95), color = "#ffffb2", name = 'C'),
        list(range = c(95, 97.5), color = '#7fbf7f', name = 'B'),
        list(range = c(97.5,100), color = "#008000", name = 'A')),
      threshold = list(
        line = list(color = "red", width = 4),
        thickness = 0.75,
        value = current_value)))

  return(fig)
}

myplot <- plot_func(current_value = 99.8)

这给出了一个输出:

我想不出办法:

  1. 有一个连续的颜色范围,而不是我现在的阶跃变化
  2. current_value 的红色条改为箭头

感谢任何帮助。

【问题讨论】:

    标签: r ggplot2 plotly gauge donut-chart


    【解决方案1】:

    制作渐变的第一个问题可以通过使用来完成 scale_*_gradient,“创建两个颜色渐变(低-高),scale_*_gradient2 创建一个发散颜色渐变(低-中-高),scale_*_gradientn 创建一个 n 色渐变。” Source

    下面的例子

    scale_colour_gradient(
      ...,
      low = "#132B43",
      high = "#56B1F7",
      space = "Lab",
      na.value = "grey50",
      guide = "colourbar",
      aesthetics = "colour"
    )
    

    至于箭头,有一个geom!

    geom_line(arrow = arrow(length=unit(0.30,"cm"), ends="first", type = "closed"))
    

    这个问题在this relevant question.中有更详细的处理

    【讨论】:

    • 谢谢,您能否提供一些示例代码,说明如何将其合并到ggplot2 - 我不知道如何将scale_colour_gradient 添加到plotly
    • @Gautam,你看到包裹flexdashboard了吗?它使您可以非常轻松地创建仪表。虽然该包不适合绘图,但它的输出可以导出到图像。 rdrr.io/cran/flexdashboard/man/gauge.html
    • flexdashboard 不太熟悉 - 似乎很有趣。但是,现在我正在寻找可以帮助我导出 html 图像或静态图像的东西——我计划使用 ggplot2(用于后者)和 plotly + orca 用于 html 图像。我需要制作大约 1000 个这样的仪表..
    • 如果你是为 HTML 做这个,我强烈建议你在 CSS 中而不是在 R 中制作仪表。
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多