Andres Mora
Andres Mora

Reputation: 1106

Line plotting on small dataset

i have this small dataset that i need to plot with plotly. Im struggling with it :/ dataset Im looking to have 3 colored lines (each line for each of the rows (1,2,3). The x axis needs to be the column names and the Y axis represents each one of the numeric values.

My code so far looks wrong

plot_ly (x = colnames(a), y = a[1], type = "scatter" ,mode = "lines" )

Upvotes: 0

Views: 46

Answers (1)

Ben
Ben

Reputation: 30474

I'm not sure that this is your desired plot, but it sounded closest to your description. I adapted a few columns of your data to describe.

The plot will be easier if data is in longer form with pivot_longer. Also easier if you add row numbers to your data so you can plot one line for each row number.

Since plotly will plot your xaxis categories alphabetically, you will want to relevel your name factor (name is your column names) to order of your columns.

In your plot_ly statement, use split to plot by row number.

library(plotly)
library(tidyverse)

a %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = -rn, names_to = "name", values_to = "value") %>%
  mutate(name = factor(name, levels = colnames(a))) %>%
  plot_ly(x = ~name, y = ~value, split = ~rn, type = "scatter", mode = "lines")

Output

plotly plot with 3 lines

Data

a <- data.frame(
  N_of_Brands = c(-.4, .8, -.4),
  Brand_Runs = c(-.26, .70, -.75),
  Total_Volume = c(-.69, .15, -.015),
  No_of_Trans = c(-.81, .45, -.35)
)

Upvotes: 1

Related Questions