R: 1 Dimensional "scatterplot" - r

I am using the R programing language. Recently, I came across this previous stackoverflow post where it describes how to make a 1 dimensional scatter plot in R: How can I plot a 1-D plot in R?:
x <- rnorm(100,10,10)
x <- data.frame(x,1) ## 1 is your "height"
plot(x, type = 'o', pch = '|', ylab = '')
My question: is it possible to transform the above plot into a "plotly" plot?
Suppose I have the following data:
library(plotly)
x <- rnorm(100,10,10)
color <- rnorm(100, 2,1)
frame = data.frame(x,color)
Would it be possible to do something like this?
fig <- plot_ly(data = frame, x = ~frame$x, color ~ frame$color )
fig
I get the following error when running this code:
No trace type specified:
Based on info supplied, a 'histogram' trace seems appropriate.
Can someone please show me how to do this?
Thanks
Source: https://plotly.com/r/line-and-scatter/

In plotly language, a trace is the type of visualization that you would like to use to display your data. So the error basically lets you know that you have not specified any trace and that the program is picking one for you: "a histogram". For scatterplots, you need type = "scatter" and mode = "markers'.
Also, inside the plot_ly() function, once you specify the data argument, you can simply access the columns with the column name preceded by a tilde ~.
Finally, since you want a one dimensional scatterplot along the x-axis, you need to add y = " " to the plot_ly() function.
This is how you can achieve your desired result:
library(plotly)
x <- rnorm(100,10,10)
color <- rnorm(100, 2,1)
frame = data.frame(x,color)
plot_ly(type = "scatter", mode = "markers", data = frame, x = ~x, y = " ", color = ~color )
Note that plotly is a very rich framework and you can read the appropriate documentation to learn how to customize your plot to your liking.

Related

Change colors for NA values to gray in R plotly scatter 3d

I'm trying to generate a plot in which I want to show NA values in translucent gray, and a set of numeric values I want to plot with a blue-red color scale. By default, plotly colors my NAs with a dark gray solid color, but I figure there must be a way to change that somehow. Is there anyway to do it? Here is a mockup of my code:
library("plotly")
blue_red <- rev(c("#A50026", "#D73027", "#F46443", "#FDAE61", "#FEE090"
, "#E0F3F8", "#ABD9E9", "#74ADD1", "#4575B4", "#313695"))
mtcars$brand <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
mtcars[mtcars$brand=="Merc","mpg"] <- NA
fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec,
marker = list(size = 6),
color=~mpg,
colors = blue_red,
type = "scatter3d",
mode = "markers")
fig
I found a somewhat similar question here: https://community.plotly.com/t/how-to-change-colors-for-na-values-to-gray-in-a-choropleth-map/15746/3 but I haven't been able to translate that to solve my problem.
Edited to make sense OK, so you have known triplets for x,y,z coordinates and you want to assign colors to various values of mpg. Can you simply do the following?
mtcars[mtcars$brand=="Merc","mpg"] <- your_chosen_value and assign a desired color to that value.
If that distorts the colors mapped to numeric values that are genuine, maybe it's simpler to plot all the non-"Merc" data with one call and then plot all the "Merc" data with a second call that uses a simple, single-value color assignment instead of your blue_red vector.

How to plot multiple y axes with plotly in R for loop

I'm trying to use a for loop to define multiple y axes in plotly graph in R. Below is an example. Does anyone have any suggestions or experience with getting something like this to work?
#example of dataset of plotly to plot multiple y axes in for loop
library(plotly)
len = length(names(mtcars))
names = names(mtcars)
n=0
p= plot_ly()
for (i in names){
n=n+1
p=add_trace(p,data = mtcars, x = mtcars[,"mpg"], y = mtcars[,i], yaxis = paste0('y',ifelse(n==1,'',n)), type = 'scatter', mode = 'scatter')
}
n=0
for (i in 1:len)
{n=n+1
layout(p,assign(paste0('yaxis', ifelse(n==1,"",n)),list( overlaying = "y", side = ifelse((n %% 2) == 0,'right','left'), title = paste0(n, " y axis")
)) )
}
p
I'm thinking that the assign with the multiple paste0's may be causing alot of problems with this. Is there any other way you all can think of to accomplish this? I'm trying to incorporate this into a shiny app to plot functions based on user input. So an lapply() or for loop is ideal. I'm not sure if I'll be able to predefine the yaxes so that all selected variables are plotted. Any help is greatly appreciated. Is there any instance of setting yaxes like this in R? It must be possible right?

R multiple lines plotly chart with customized line types

I have probably a simple R plotly question but I spent about one hour reading questions in stackoverflow and I really can't find what I need. I have a dataframe (I will share a screenshot) with different columns used to create a multiple lines plotly chart.
This is the code I use to create the plot:
plot_ly(data = df_final, x=~TENOR, y=~RATE) %>% add_trace(type='scatter',mode='lines', color=~LINE_NAME, colors = ~LINE_COL) %>%
layout(title=paste0("Market data"),
xaxis=list(title='Term (years)'),
yaxis=list(title='Yield'))
it works amazing but I would like to have the option to choose if some lines will have to be dashed, dots, or solid lines as well as their width.
I would need / want to specify this information inside the dataframe and choose the dataframe column that has such information (i.e. see the column "LINE_STYLE_FACTOR" in my attached dataframe).
I checked Multiple line chart using plotly r and Plotly r, line style by variable but I can't find how to do what I need.
The solution has to use plotly and not other charting solutions.
Thanks
At least for the line types (dash vs line), you can you 'linetype':
library(dplyr)
library(plotly)
df = data.frame(xVals = rep(1:10,2),
yVals = c(1:10, 2:11),
myColor = c(rep('Red', 10), rep('Blue', 10)),
myType = c(rep('solid', 10), rep('dot', 10)),
myName = c(rep('FirstName', 10), rep('SecondName', 10)))
plot_ly(df,
x = ~xVals,
y = ~yVals,
color = ~I(myColor),
name = ~myName,
type = 'scatter',
mode = 'lines',
linetype = ~I(myType)
)

Categorical axes in plotly heatmapgl

Hi I've some problems with heatmapgl plot (but with heatmap I get the same) of plotly package.
I've a distance matrix between a series of elements. I would like to plot a heatmap with names of elements on axes and possibly also on hover text labels.
library(plotly)
values=c(22.63409, 323.93780, 366.31498, 467.94524, 461.93251, 643.61306, 665.03471, 482.49047, 500.06208, 662.71600, 673.29995, 567.99427, 558.41419, 632.86704, 615.55000, 508.01659, 462.50232, 411.39160, 399.00598, 286.55681, 268.69871)
z_matrix=matrix(NA,7,7)
z_matrix[lower.tri(z_matrix, diag=FALSE)] <- values
elements_names=c("ATHOTPlun04", "ATHOTPlun10", "ATHOTPlun16", "ATHOTPlun22", "ATHOTPmar04", "ATHOTPmar10", "ATHOTPmar16")
q <- plot_ly(
x=elements_names,
y=elements_names,
z = z_matrix, type = "heatmapgl") %>%
layout(title = 'Distances for ATHOTP route')
q
Although this is what I get when I run the code:
I tried also to set axes type to "category" in layout options but nothing seems to change. What am I missing? Thank you!
heatmap-gl is used for images where you have continuous x- and y-axes. Therefore you need to change type to a non-continuous type, e.g. type = "heatmap".
q <- plot_ly( x=elements_names,
y=elements_names,
z = z_matrix, type = "heatmap") %>%
layout(title = 'Distances for ATHOTP route')
q

Visualize data using histogram in R

I am trying to visualize some data and in order to do it I am using R's hist.
Bellow are my data
jancoefabs <- as.numeric(as.vector(abs(Janmodelnorm$coef)))
jancoefabs
[1] 1.165610e+00 1.277929e-01 4.349831e-01 3.602961e-01 7.189458e+00
[6] 1.856908e-04 1.352052e-05 4.811291e-05 1.055744e-02 2.756525e-04
[11] 2.202706e-01 4.199914e-02 4.684091e-02 8.634340e-01 2.479175e-02
[16] 2.409628e-01 5.459076e-03 9.892580e-03 5.378456e-02
Now as the more cunning of you might have guessed these are the absolute values of some model's coefficients.
What I need is an histogram that will have for axes:
x will be the number (count or length) of coefficients which is 19 in total, along with their names.
y will show values of each column (as breaks?) having a ylim="" set, according to min and max of those values (or something similar).
Note that Janmodelnorm$coef simply produces the following
(Intercept) LON LAT ME RAT
1.165610e+00 -1.277929e-01 -4.349831e-01 -3.602961e-01 -7.189458e+00
DS DSA DSI DRNS DREW
-1.856908e-04 1.352052e-05 4.811291e-05 -1.055744e-02 -2.756525e-04
ASPNS ASPEW SI CUR W_180_270
-2.202706e-01 -4.199914e-02 4.684091e-02 -8.634340e-01 -2.479175e-02
W_0_360 W_90_180 W_0_180 NDVI
2.409628e-01 5.459076e-03 -9.892580e-03 -5.378456e-02
So far and consulting ?hist, I am trying to play with the code bellow without success. Therefore I am taking it from scratch.
# hist(jancoefabs, col="lightblue", border="pink",
# breaks=8,
# xlim=c(0,10), ylim=c(20,-20), plot=TRUE)
When plot=FALSE is set, I get a bunch of somewhat useful info about the set. I also find hard to use breaks argument efficiently.
Any suggestion will be appreciated. Thanks.
Rather than using hist, why not use a barplot or a standard plot. For example,
## Generate some data
set.seed(1)
y = rnorm(19, sd=5)
names(y) = c("Inter", LETTERS[1:18])
Then plot the cofficients
barplot(y)
Alternatively, you could use a scatter plot
plot(1:19, y, axes=FALSE, ylim=c(-10, 10))
axis(2)
axis(1, 1:19, names(y))
and add error bars to indicate the standard errors (see for example Add error bars to show standard deviation on a plot in R)
Are you sure you want a histogram for this? A lattice barchart might be pretty nice. An example with the mtcars built-in data set.
> coef <- lm(mpg ~ ., data = mtcars)$coef
> library(lattice)
> barchart(coef, col = 'lightblue', horizontal = FALSE,
ylim = range(coef), xlab = '',
scales = list(y = list(labels = coef),
x = list(labels = names(coef))))
A base R dotchart might be good too,
> dotchart(coef, pch = 19, xlab = 'value')
> text(coef, seq(coef), labels = round(coef, 3), pos = 2)

Resources