如何在 plotly R 中为通过 add_trace 创建的饼图添加单独的标题

How to add seperate titles to pie charts created through add_trace in plotly R

我正在尝试使用相同的数据集创建几个饼图,但值变量在数据集中将是不同的列名。我需要帮助为每个打印的饼图打印不同的标题。

下面是代码 using:Expectation 在每个饼图下面我想打印一个标题为 'mpg'、'disp'、'hp' 等。因为这些是用作值变量的观察值。

        xmtcars<-tibble::rownames_to_column(mtcars,'carname')


           plot_ly(data = xmtcars)%>% add_trace(
           labels =  ~ carname,
           values =  ~ mpg,
           type = 'pie',
            textinfo = 'none',
            name = 'mpg',
            domain = list(x = c(0.0, .1667), y = c(0, 1)))%>% add_trace(
            labels =  ~ carname,
            values =  ~ cyl,
            type = 'pie',
            textinfo = 'none',
            name = 'cyl',
            domain = list(x = c(0.1667, .333), y = c(0, 1))
    )%>% add_trace(
            labels =  ~ carname,
            values =  ~ disp,
            type = 'pie',
            textinfo = 'none',
            name = 'disp',
            domain = list(x = c(0.333, .5), y = c(0, 1))
    )%>% add_trace(
            labels =  ~ carname,
            values =  ~ hp,
            type = 'pie',
            textinfo = 'none',
            name = 'hp',
            domain = list(x = c(.5, .667), y = c(0, 1))

    )%>% add_trace(
            labels =  ~ carname,
            values =  ~ drat,
            type = 'pie',
            textinfo = 'none',
            name = 'drat',
            domain = list(x = c(.667, .833), y = c(0, 1))

    )%>% add_trace(
            labels =  ~ carname,
            values =  ~ wt,
            type = 'pie',
            textinfo = 'none',
            name = 'wt',
            domain = list(x = c(0.833, 1), y = c(0, 1))

    ) %>%layout(
            title = "Analysis by cars",
            showlegend = T,
            xaxis = list(
                    showgrid = F,
                    zeroline = FALSE,
                    showticklabels = T
            ),
            yaxis = list(
                    showgrid = F,
                    zeroline = FALSE,
                    showticklabels = T
            )
    )

感谢一些帮助。

您可以使用add_annotations并单独设置馅饼的标题。

只需添加这行代码:

%>% add_annotations(x=seq(0.06,0.06 + 5*0.17,0.17),
                y=0.3,
                text = c("mpg", "cyl", "disp","hp","drat","wt"),
                xref = "paper",
                yref = "paper",
                xanchor = "left",
                showarrow = FALSE
                )

这是输出: