r-如何始终在高级图形对象上显示标签

时间:2016-08-10 06:34:50

标签: javascript r highcharts

我使用了一个包含饼图和条形图的高图对象,标签(百分比)显示只有鼠标移动到它上面。请参阅以下代码:

library(highcharter)
data("favorite_bars")
data("favorite_pies")

highchart() %>% 
hc_title(text = "This is a bar graph describing my favorite pies
        including a pie chart describing my favorite bars") %>%
hc_subtitle(text = "In percentage of tastiness and awesomeness") %>% 
hc_add_series_labels_values(favorite_pies$pie, favorite_pies$percent, name = "Pie",
                          colorByPoint = TRUE, type = "column") %>% 
hc_add_series_labels_values(favorite_bars$bar, favorite_bars$percent,
                          colors = substr(terrain.colors(5), 0 , 7), type = "pie",
                          name = "Bar", colorByPoint = TRUE, center = c('35%', '10%'),
                          size = 100, dataLabels = list(enabled = FALSE)) %>% 
hc_yAxis(title = list(text = "percentage of tastiness"),
       labels = list(format = "{value}%"), max = 100) %>% 
hc_xAxis(categories = favorite_pies$pie) %>% 
hc_legend(enabled = FALSE) %>% 
hc_tooltip(pointFormat = "{point.y}%") %>% 
hc_credits(enabled = TRUE, text = "Source: HIMYM",
         href = "https://www.youtube.com/watch?v=f_J8QU1m0Ng",
         style = list(fontSize = "12px"))

我希望百分比始终显示而不是鼠标移动。看看我从highcharts官方网站获得的图片:   enter image description here   enter image description here

1 个答案:

答案 0 :(得分:5)

您可以在highcharts website上看到用于创建粘贴饼图的选项,方法是点击查看选项

您将看到以下代码:

plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },

这意味着您必须启用dataLabels选项并提供格式化程序。在您提供的代码中,您实际上可以在第二次hc_add_series_labels_values调用中看到dataLabels enabled选项设置为FALSE

hc_add_series_labels_values(favorite_bars$bar, favorite_bars$percent,
                          colors = substr(terrain.colors(5), 0 , 7), type = "pie",
                          name = "Bar", colorByPoint = TRUE, center = c('35%', '10%'),
                          size = 100, dataLabels = list(enabled = FALSE))

如果您将其更改为TRUE,您会看到标签。如果你想要显示数字,你必须将一个函数传递给列表中的format元素,如下所示:

hc_add_series_labels_values(favorite_bars$bar, favorite_bars$percent,
                              colors = substr(terrain.colors(5), 0 , 7), type = "pie",
                              name = "Bar", colorByPoint = TRUE, center = c('35%', '10%'),
                              size = 100, dataLabels = list(enabled = TRUE,
                                                            format = '{point.name}: {point.percentage:.1f} %')) 

然后,您必须使用dataLabels的不同选项来显示它们,但请参阅条形图类型的Highcharts API