I am trying to add a horizontal line to each state based on each state's unique Murder rate. Here is my attempted code. Unfortunately, I am not open to using other functions like Shiny because essentially I would like to create an html output from R markdown for my job
Here is my code.Essentially,I created a drop-down select menu so when you select on each state, the Assault, UrbanPop, Rape, and Murder values would automatically change based on the state selected.
At the moment, I created a horizontal line using the murder rate of Alabama (13.2) but I would like to create one based on each state ( ex: Alaska, Murder = 10).
I am also having trouble aligning the text to the top of the line on the right. Any help would be appreciated!
library(tidyverse)
library(reshape2)
library(plotly)
library(crosstalk)
data("USArrests")
arrests = rownames_to_column(USArrests, var = "state")
alabama <- arrests %>% filter(state == "Alabama")
arrests <- melt(arrests, id.vars=c("state"))
arrests <- arrests[order(arrests$value),]
# Round 'value' field to 1 decimal
arrests <- arrests %>% mutate(value = round(value, 1))
sd1 <- SharedData$new(arrests, key = ~ state)
hline <- function(y = 0, color = "black") {
list(
type = "line",
x0 = 0,
x1 = 1,
xref = "paper",
y0 = y,
y1 = y,
line = list(color = color),
text = "12"
)
}
bscols(
widths = 7,
filter_select("state", ## this is the name of column we want to select.
"State:", # this is what we want to see in the selection menu
sd1,
~ state, multiple = FALSE),
plot_ly(sd1) %>%
add_trace(x = ~ variable, y = ~ value, type = "bar", color = I("yellow"),
marker = list(line = list(color = "black", width =1)) ## add order t
) %>%
layout(barmode = "stack",
xaxis = list(title = 'Column',
tickangle=-45,
categoryorder = "total descending"),
yaxis = list(title = ''),
width = 600,
paper_bgcolor = "#FFFFFF",
plot_bgcolor = "#FFFFFF",
font = list(
family = "Rubik",
size = 12,
color = '#8E8C8F'
),
hoverlabel = list(align = "right"),
shapes = list(hline(alabama$Murder))
)
%>% add_text(
showlegend = FALSE, x = 0, y = alabama$Murder,
text = paste0("Murder Rate: ",round(alabama$Murder, 1))
)
)