I wrote a code to make a subplots with scatterplots using my data. Here is a graph:
This is hours on x axis. As you see, not all of them appear on x axis. How could i make all 24 hours be on axis? Even if for example in dataframe there is no value for 23 o'clock, i want it to be on x axis. How to do that?
Here is my code:
plot <- function(df) {
subplotList <- list()
for(metric in unique(df$metrics)){
subplotList[[metric]] <- df[df$metrics == metric,] %>%
plot_ly(
x = ~ hr,
y = ~ actual,
name = ~ paste(metrics, " - ", time_pos),
colors = ~ time_pos,
hoverinfo = "text",
hovertemplate = paste(
"<b>%{text}</b><br>",
"%{xaxis.title.text}: %{x:+.1f}<br>",
"%{yaxis.title.text}: %{y:+.1f}<br>",
"<extra></extra>"
),
type = "scatter",
mode = "lines+markers",
marker = list(
size = 7,
color = "white",
line = list(width = 1.5)
),
width = 700,
height = 620
) %>% layout(autosize = T,legend = list(font = list(size = 8)))
}
subplot(subplotList, nrows = length(subplotList), margin = 0.05)
}
This could be achieved in layout via the attribute xaxis like so. The ticks or breaks can be set via tickvals, the tick labels via ticktext.
This is illustrasted using some random data in the reproducible example below:
library(plotly)
set.seed(42)
d <- data.frame(
x = sort(sample(24, 15)),
y = 1:15 + runif(15),
z = 1:15 + runif(15)
)
plot_ly(d) %>%
add_trace(x = ~x, y = ~y, type = "scatter", mode = "lines+markers") %>%
add_trace(x = ~x, y = ~z, type = "scatter", mode = "lines+markers") %>%
layout(xaxis = list(tickvals = 1:24, ticktext = paste0(1:24, "h")))
Related
Consider the following code
set.seed(1234)
r = rnorm(200)
ir = cumsum(r)
df = data.frame(low = ir - 2*abs(r), high = ir + 2*abs(r), mid = ir, x = 1:200)
df[90:110,] <- NA
plot_ly(data = df) |>
add_lines(x = ~x, y = ~high, line = list(width = 2), name = "high") |>
add_lines(x = ~x, y = ~low, fillcolor='rgba(0,100,80,0.2)', fill = "tonexty", line = list(width = 2), name = "low") |>
add_lines(x = ~x, y = ~mid, line = list(color = "black"), name = "mid")
which generates the following chart
I want to have a break in the chart where the data is missing, and I want to fill the area between the lines, but I don't want this weird artifact you can see. Any ideas?
The dynamic hoverlabel background color in R plotly does not seem to work when using scattergl instead of scatter as depicted in the example below.
Works as intended with type = "scatter":
library(plotly)
X <- data.frame(x = 1:6,
y = 1:6,
z = 1:6)
plot_ly(data = X, x = ~x, y = ~y,
type = "scatter", mode = "markers",
marker = list(color = ~x,
colorscale = list(c(0, .5, 1), c('#0d71db', "#dbc00d", "#db220d"))))
The hoverlabel background color becomes black for all data points with type = "scattergl":
plot_ly(data = X, x = ~x, y = ~y,
type = "scattergl", mode = "markers",
marker = list(color = ~x,
colorscale = list(c(0, .5, 1), c('#0d71db', "#dbc00d", "#db220d"))))
I guess a solution could be to pass the same color array used in colorscale to the bgcolor argument via hoverlabel = list(bgcolor = ???). However I have no idea how to do so.
Edit
Tried this based on #Quinten's answer, without success. As can be seen the colors are the default plot_ly colors and do not correspond to what is specified in cols.
library(plotly)
n <- 5000
X <- data.frame(x = sample(1:100, n, replace = TRUE),
y = sample(1:100, n, replace = TRUE),
z = sample(1:500, n, replace = TRUE))
length_unique_vals <- length(unique(X$z))
cols <- colorRampPalette(c('#0d71db', "#dbc00d", "#db220d"))(length_unique_vals)
cols <- cols[factor(X$z)]
plot_ly(data = X, x = ~x, y = ~y,
type = "scattergl", mode = "markers",
marker = list(color = ~z,
colorscale = cols,
colorbar = list(title = "Colorbar")),
hoverlabel = list(bgcolor = cols)) %>%
toWebGL()
You can create a vector of 6 different colors using RColorBrewer. These colors you assign to the color of your marker and to the bgcolor of your hoverlabel which will show the right color. You can use the following code:
library(plotly)
X <- data.frame(x = 1:6,
y = 1:6,
z = 1:6)
library(RColorBrewer)
cols <- brewer.pal(n = 6, name = "Set3")
plot_ly(data = X, x = ~x, y = ~y,
type = "scattergl", mode = "markers",
marker = list(color = cols),
hoverlabel = list(bgcolor = cols))
Output:
As you can see from the plot, the label is the same color as the marker.
I am working with the R Programming language.
Using the following link as a tutorial (https://plotly.com/r/lines-on-maps/), I was able to make an interactive plot:
#load libraries
library(dplyr)
library(leaflet)
library(plotly)
library(data.table)
#generate data for example (longitude and latitude of cities)
lat = rnorm(100, 43, 3)
long = rnorm(100, -79, 3)
map_data = data.frame(lat, long)
map_data$type = as.factor(1:100)
#change format of the data so that it is compatible for this example
result = rbind(
cbind(map_data[1:nrow(map_data)-1,c(1,2)], map_data[-1,c(1,2)]),
cbind(map_data[nrow(map_data), c(1,2)], map_data[1,c(1,2)])
)
colnames(result) <- c("start_lat", "start_long", "end_lat", "end_long")
my_data = result
my_data$type = as.factor(1:nrow(my_data))
my_data$type1 = as.character(1:100)
my_data$count = as.integer(1)
my_data$id = 1:100
#### begin visualization
# map projection
geo <- list(
scope = 'north america',
projection = list(type = 'azimuthal equal area'),
showland = TRUE,
landcolor = toRGB("gray95"),
countrycolor = toRGB("gray80")
)
fig <- plot_geo(locationmode = 'USA-states', color = I("red"))
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat, alpha = 0.5
)
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat, hoverinfo = "text", alpha = 0.5
)
fig <- fig %>% add_segments(
data = group_by(my_data, type),
x = ~start_long, xend = ~end_long,
y = ~start_lat, yend = ~end_lat,
alpha = 0.3, size = I(1), hoverinfo = "none"
)
fig <- fig %>% layout(
title = 'Plot 1',
geo = geo, showlegend = FALSE, height=800
)
#final result
fig
This produces the following result:
Now, I am trying to get the "interactive text" to work:
# map projection
geo <- list(
scope = 'north america',
projection = list(type = 'azimuthal equal area'),
showland = TRUE,
landcolor = toRGB("gray95"),
countrycolor = toRGB("gray80")
)
fig <- plot_geo(locationmode = 'USA-states', color = I("red"))
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat, alpha = 0.5
)
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat, text = ~type1, size = ~count, hoverinfo = "text", alpha = 0.5
)
fig <- fig %>% add_segments(
data = group_by(my_data, type),
x = ~start_long, xend = ~end_long,
y = ~start_lat, yend = ~end_lat,
alpha = 0.3, size = I(1), hoverinfo = "none"
)
fig <- fig %>% layout(
title = 'Plot 1',
geo = geo, showlegend = FALSE, height=800
)
fig
The interactive text is now working, but the data points are appearing "much bulkier".
My Question: Is it possible to make the interactive text work, but have the data points appear the same way they do in the first picture?
I originally tried to do this without a "count" variable:
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat, text = ~type1, hoverinfo = "text", alpha = 0.5
)
But when I do this, the interactive text isn't working - the interactive text only works when a "count" variable is added.
Is this "count" variable necessary? Can someone please show me how to fix this?
Thanks!
You don't need to use count. However, there is something odd here with the segments. Either way, this achieves what I think you're looking for.
I have provided two examples because you didn't say what you wanted to have in the hover text. In the first example, I just use the x and y (lat and long). In the second, I used custom hover content.
Everything that precedes the creation of fig was left unchanged.
Notable changes:
the order the fig elements are assembled; segments seems to only work if it is before the markers
hoverinfo for the segments add is now set to text--this didn't add hover content, but for some reason none here was a problem...odd
I dropped a call to fig or two, that seemed to be doing nothing...
in add_markers, this changed differently in the two options
in one, hovertext = "text" was changed to hovertext = "lat+lon"
in the other, there were multiple changes--you'll have to look at the code for this one
in layout, I deleted the height argument; it's ignored
fig <- plot_geo(locationmode = 'USA-states', color = I("red"))
fig <- fig %>% add_segments( # add segments
data = group_by(my_data, type),
x = ~start_long, xend = ~end_long,
y = ~start_lat, yend = ~end_lat,
alpha = 0.3, size = I(1), hoverinfo = "text" # changed hoverinfo
)
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat,
alpha = 0.5, hoverinfo = "lat+lon" # changed hoverinfo
)
fig <- fig %>% layout(
title = 'Plot 1',
geo = geo, showlegend = FALSE # removed height argument
)
#final result
fig
Here's the custom text version
fig <- plot_geo(locationmode = 'USA-states', color = I("red"))
fig <- fig %>% add_segments( # add segments
data = group_by(my_data, type),
x = ~start_long, xend = ~end_long,
y = ~start_lat, yend = ~end_lat,
alpha = 0.3, size = I(1), hoverinfo = "text" # changed hoverinfo
)
fig <- fig %>% add_markers(
data = my_data, x = ~start_long, y = ~start_lat,
alpha = 0.5, hoverinfo = "text", # hoverinfo unchanged
text = ~paste0("Longitude: ", # text changed here**
round(my_data$start_long, 2),
"<br>Latitude: ",
round(my_data$start_lat, 2))
)
fig <- fig %>% layout(
title = 'Plot 1',
geo = geo, showlegend = FALSE # removed height argument
)
#final result
fig
Let me know if you have any questions!
I have a plot using plotly r . As of now the variations cant be seen that much. So in order to do so if the y-axis is 0-70% is there a way to show just 50%-70% on y axis so the variation can be seen more clearly.
Below is code I am using
output$plot <- renderPlotly({
if (is.null(ab()))
return(NULL)
y <- list(title = "Percentange")
x <- list(title = "Months")
plot_ly(ab(), x = ~ Month_considered, y = ~ pct * 100,type = 'scatter', mode = 'marker',
fill = 'tozeroy', line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%layout(xaxis = x, yaxis = y)})
You don't provide a reproducible example so it is hard to test, but you could try:
y <- list(title = "Percentage", range = c(50,70))
plot_ly(ab(), x = ~ Month_considered, y = ~ pct * 100,type = 'scatter', mode = 'marker', fill = 'tozeroy', line = list(color = 'rgb(205, 12, 24)', width = 4)) %>% layout(xaxis = x, yaxis = y)})
Here is my data:
set.seed(42)
mydata = data.frame(A = rnorm(20), B = rnorm(20), Index = sample(190:400,20))
I am trying to divide the data into 20 different intervals based on the Index value and then color the scatter points according to their interval value. Below is my code. It is not working perfectly.
cols = colorRampPalette(c("red", "black"), space = "rgb")(20)
mydata$interval = cut(mydata$Index,breaks = 20)
mydata$cols = cols[mydata$interval]
require(plotly)
x = list(title = "A")
y = list(title = "B")
plot_ly(mydata, x = ~A, y = ~B, color = ~cols, type = "scatter",
mode = 'markers', hoverinfo = 'text',
text = ~paste(interval)) %>%
layout(xaxis = x, yaxis = y)
How do I get a colorbar in the legend where the colors are based on Index value.
Are you looking for this:
plot_ly(mydata, x = ~A, y = ~B, type = "scatter",
mode = 'markers', hoverinfo = 'text', colors = colorRampPalette(c("red", "black"), space = "rgb")(20), color = ~Index, text = ~paste(interval), marker = list(size=14)) %>%
layout(xaxis = x, yaxis = y) %>%
colorbar(title = "My Legend")