我有一个整洁的数据框,类似于以下内容:
tidyDF <- data.frame(PORT_NAME = c("South Louisiana, LA, Port of",
"Houston, TX", "Long Beach, CA",
"New York, NY and NJ",
"Los Angeles, CA", "Beaumont, TX",
"Corpus Christi, TX", "New Orleans, LA",
"Baton Rouge, LA", "Mobile, AL"),
TOTAL_TONS = c(267390209, 234304391, 170052128,
126158655, 122033848, 87283716, 84928330,
84465052, 69185878, 64287565),
portSel = c("NO", "NO", "NO", "NO", "NO", "YES",
"NO", "NO", "NO", "NO"))
我想根据 portSel
变量创建一个具有特定颜色的条形图。
这是我使用的代码:
library(highcharter)
myColors <- c("#002F80", "#F9AF38")
highchart() %>%
hc_add_series_df(data = tidyDF,
type = "bar",
x = PORT_NAME,
y = TOTAL_TONS,
group = portSel) %>%
hc_xAxis(title = list(text = "Ports"),
tickmarkPlacement = "on",
tickLength = 0,
labels = list(
enabled = FALSE
)) %>%
hc_yAxis(title = list(text = "2014 Total Tonnage")) %>%
hc_legend(enabled = FALSE) %>%
hc_colors(myColors)
我在hc_add_series_df
中尝试了group
和color
。两者都不能正常工作。当我使用 group = portSel
时,颜色是正确的,但它将单个 YES 端口移动到与第一个 NO 端口组合在一起。当我使用 color = portSel
时,它会将 YES 端口放在正确的位置,但它不再使用 myColors
中的自定义颜色。
欢迎任何建议! 谢谢。
最佳答案
我修改了之前的答案。
您没有以正确的方式使用群组。 group
选项是创建/添加多个系列,这就是第一个 yes
的原因在第一个no
旁边因为值是有序的。
关于颜色,函数hc_add_series_df
根据给定的颜色变量为点(条、柱)着色,因此不要使用 hc_colors
给出的颜色.
因此,我认为一种简单的方法是“手动”添加系列。这意味着使用您想要的特定数据(和颜色)从数据中创建一个列表。
tidyDF2 <- tidyDF %>%
mutate(color = ifelse(portSel == "NO", myColors[1], myColors[2])) %>%
select(y = TOTAL_TONS, color)
highchart() %>%
hc_chart(type = "bar") %>%
hc_xAxis(labels = list(
enabled = FALSE
)) %>%
hc_add_series(data = list_parse(tidyDF2), showInLegend = FALSE)
这对你有帮助吗?
上一个答案。
您可以尝试添加 hc_xAxis
下一个参数:type = "categorical", categories = tidyDF$PORT_NAME,
并在 hc_add_series_df
中使用组.您会看到一个带有"is"列的条形图,因为您放置了 2 个系列(每组一个),例如 http://www.highcharts.com/demo/column-parsed。
highchart() %>%
hc_add_series_df(data = tidyDF,
type = "bar",
x = PORT_NAME,
y = TOTAL_TONS,
group = portSel) %>%
hc_xAxis(title = list(text = "Ports"),
type = "categorical",
categories = tidyDF$PORT_NAME,
tickmarkPlacement = "on",
tickLength = 0,
labels = list(
enabled = TRUE
)) %>%
hc_yAxis(title = list(text = "2014 Total Tonnage")) %>%
hc_legend(enabled = FALSE) %>%
hc_colors(myColors)
关于r highcharter package 条形图组与颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286297/