I have a tidy dataframe, similar to the following:
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"))
I would like to create a barplot with specific colors based on the portSel variable.
Here is the code I am using:
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)
I have tried both group and color in hc_add_series_df. Neither work correctly. When I use group = portSel, as above, the colors are correct, but it moves the single YES port to be grouped with the first NO port. When I use color = portSel, it puts the YES port in the correct spot, but it no longer uses the custom colors in myColors.
Any advice is welcome!
Thanks.
I modified the previous answer.
You're not using groups in the right way. The group option is to create/add more than 1 series, that's why the first yes is next to the first no because the value are put in order.
About the colors, the function hc_add_series_df colorize the points (bars, column) according the given color variable so don't use the color given by hc_colors.
So, I think a simple way to do this is add the series "manually". This means craete a list from the data with the specific data (and color) that you want.
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)
Does this help you?
Previous answer.
You can try add in hc_xAxis the next arguments: type = "categorical", categories = tidyDF$PORT_NAME, and use just group in hc_add_series_df. You will see a bar chart with the "yes" column a little displace due you put 2 series (one for each group), for example 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)
Related
I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:
I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:
library(plotly)
library(dplyr)
data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
scope = 'world',
countrycolor = toRGB('grey'),
showframe = T,
showcoastlines = TRUE,
projection = list(type = 'natural earth')
)
map.time = data %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
map.time
Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.
The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.
map.time = data %>%
mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code,
marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
Which gives:
I'm trying to create a bar chart showing Cost of Living indexed to the U.S. value (100) in the Highcharter package in R. So I want the bars the start at 100 and either extend to the right or the left of 100. I have the basic bar chart down, but I can't figure out how to move the center line of the chart to 100. I'm trying to get it to look something like this: http://drawingwithnumbers.artisart.org/moving-the-center-line-of-a-bar-chart-with-a-gantt-chart/
Here's the data I'm working with:
States <- c('Tennessee','Michigan','Indiana','Ohio','Kentucky','West Virginia','North Carolina','Virginia','Pennsylvania','Delaware','New Jersey','Maryland','New York')
Cost_of_Living <- c(88.7,88.9,90,90.8,90.9,91.1,94.9,100.7,101.7,108.1,125.1,129.7,139.1)
costliving <- data.frame(States, Cost_of_Living)
And here's the code I have for the bar chart, just the basic bar chart
costliving_graph <- highchart() %>%
hc_title(text = "Cost of Living by State (2020)") %>%
hc_add_series (costliving, "bar", hcaes(x = States, y = Cost_of_Living)) %>%
hc_xAxis(categories = costliving$States) %>%
hc_yAxis(title = list(text = "Indexed to the U.S. (U.S. Value = 100)"))%>%
hc_plotOptions (bar = list(colorByPoint = TRUE)) %>%
hc_legend (enabled = FALSE)%>%
hc_tooltip(pointFormat = "MSA Regional Price Parities: {point.y}", headerFormat ="")
costliving_graph
Any help would be great! Thanks in advance
After checking examples on highcharter website I changed the charttype to columnrange and added new vars low and high to the dataframe. Try this:
library(highcharter)
library(dplyr)
States <- c('Tennessee','Michigan','Indiana','Ohio','Kentucky','West Virginia','North Carolina','Virginia','Pennsylvania','Delaware','New Jersey','Maryland','New York')
Cost_of_Living <- c(88.7,88.9,90,90.8,90.9,91.1,94.9,100.7,101.7,108.1,125.1,129.7,139.1)
costliving <- data.frame(States, Cost_of_Living) %>%
mutate(low = pmin(Cost_of_Living, 100),
high = pmax(Cost_of_Living, 100))
costliving_graph <- highchart() %>%
hc_title(text = "Cost of Living by State (2020)") %>%
hc_add_series(costliving, "columnrange", hcaes(x = States, y = Cost_of_Living, low = low, high = high)) %>%
hc_xAxis(categories = costliving$States) %>%
hc_yAxis(title = list(text = "Indexed to the U.S. (U.S. Value = 100)"))%>%
hc_plotOptions (bar = list(colorByPoint = TRUE)) %>%
hc_legend (enabled = FALSE)%>%
hc_tooltip(pointFormat = "MSA Regional Price Parities: {point.y}", headerFormat ="")
costliving_graph
I noticed that my bar graphs change in order based on alphabetical order. I'm using a selectinput, thus if a person who is selected with a name beginning in A, they are at the top, but if it is a letter after C, then they move to the bottom. This is not based on the value of the bars, but seems tied to the names. How can I keep the ProviderName at top always?
My hc code is below
hchart(
comparison_prov_df,
type = "bar",
hcaes(x = Metric, y = Value, group = ProviderName),
colorByPoint = F,
showInLegend = T,
dataLabels = list(enabled = T)
) %>%
hc_chart(zoomType = "xy") %>%
hc_tooltip(crosshairs = TRUE, shared = FALSE, borderWidth = 1) %>%
hc_credits(
enabled = TRUE,
text = ""
) %>%
hc_add_theme(hc_theme_elementary()) %>%
hc_legend(enabled = TRUE) %>%
hc_exporting(
enabled = TRUE,
filename = "data"
) %>%
hc_title(
text = "Title",
align = "left"
) %>%
hc_yAxis(
title = list(text = "Y Axis"),
labels = list(
reserveSpace = TRUE,
overflow = "justify"
)
) %>%
hc_xAxis(title = "") %>%
hc_tooltip(pointFormat = "{point.y:.1f}")
I am not sure what the original data is like, but I'll provide a simple example of one way to change the order of items on an axis. You can change the order by simply using hc_xAxis and then listing the category order.
library(highcharter)
library(tidyverse)
df %>%
hchart("bar", hcaes(x = category, y = value, group = group)) %>%
hc_xAxis(
categories = list(
"Pineapples",
"Strawberries",
"Apples",
"Plums",
"Blueberries",
"Oranges"
)
)
Output
Data
set.seed(326)
df <-
data.frame(category = rep(c(
"Apples", "Oranges", "Plums", "Pineapples", "Strawberries", "Blueberries"
), each = 2),
value = round(runif(12, min = 0, max = 100)),
group = rep(c(2020, 2021), 6))
I tried to make interactive map using R shiny which will show plot of male and female citizens in some cities. Data frame sample is shown below.
df1 <- read.table(header = TRUE, text = "city,year,male,female,long,lat
A,2017,1038,876,35.54331,139.12333
A,2018,1281,911,35.54331,139.12333
B,2017,832,517,35.14189,140.664113
B,2018,914,589,35.14189,140.664113", sep = ",")
df2 <- df1
The interactive map is built by using leaflet package and if the city marker is clicked, a plot which built by highchart will be shown.
output$chart <- renderHighchart({
df2 <- df1[df1$city == click_marker(),]
hchart() %>%
hc_add_series(df2, "column", hcaes(x = year, y = male, group = city, name = "Male")) %>%
hc_add_series(df2, "column", hcaes(x = year, y = female, group = city, name = "Female")) %>%
hc_xAxis(title = list(text = "Year")) %>%
hc_yAxis(title = list(text = "Amount (Thousands)"))
})
highchartOutput('chart')
I expect the output is a plot that show amount of male and female in the city for each year given but the output that I got is "argument object is missing, with no default."
What if you change hchart to highchart and the names to lowercase? Apparently they have to be found in the data.frame.
highchart() %>%
hc_add_series(df2, "column", hcaes(x = year, y = male, group = city, name = "male")) %>%
hc_add_series(df2, "column", hcaes(x = year, y = female, group = city, name = "female")) %>%
hc_xAxis(title = list(text = "Year")) %>%
hc_yAxis(title = list(text = "Amount (Thousands)"))
I'm trying to get the value in the province label from this example:
library("dplyr")
library('highcharter')
library("viridisLite")
data("USArrests", package = "datasets")
data("usgeojson")
USArrests <- USArrests %>%
mutate(state = rownames(.))
highchart() %>%
hc_title(text = "Violent Crime Rates by US State") %>%
hc_subtitle(text = "Source: USArrests data") %>%
hc_add_series_map(usgeojson, USArrests, name = "Murder arrests (per 100,000)",
value = "Murder", joinBy = c("woename", "state"),
dataLabels = list(enabled = TRUE,
format = '{point.properties.postalcode}'))
I want to have the value 'Murder' from the USArrests in the dataLabels rather than the state abbr. How should this be done?
Thanks,
Tim
To change dataLabels format you could add map serie like:
hc_add_series_map(usgeojson, USArrests, name = "Murder arrests (per 100,000)",
value = "Murder", joinBy = c("woename", "state"),
dataLabels = list(enabled = TRUE,
format = '{point.value}'))
Important here is format = '{point.value}' - this will make Highcharts use value of a point and a value is set in point from "Murder" (value = "Murder").