简体   繁体   中英

Colors on the x-axis labels in plotly R

I'd like to set different colors for date labels on the x axis so that each month has a different color. I'm trying to use the ifelse function and I'm doing something incorrectly.

today <- Sys.Date()
tm <- seq(0, 100, by = 1)
x <- today + tm
y <- rnorm(length(x))
TD<-data.frame(date=x, value=y)

a<-ifelse(grepl("2019-12", TD$date), "red", "blue")

ggplot(data = TD, aes(x = date, y = value)) + 
  geom_line() + 
  scale_x_date(date_labels = "%d-%m-%Y", breaks = date_breaks("2 day")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = a))

在此处输入图片说明

Edit date:

today <- Sys.Date()
tm <- seq(0, 100, by = 1)
x <- today + tm
y <- rnorm(length(x))
plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'lines')  %>%
  layout(
      xaxis = list(
      type = 'date',
      tickformat = "%d %b %Y"
      ))

There are 2 things happening. Your vector a is too long for coloring. You are not showing 101 labels. 2nd, ggplot expands the x-axis a little bit on both sites, adding labels. This makes it a bit difficult to calculate how many december 2019 labels there are. This means that you first have to make the plot, check how many labels are from december 2019 and then you can add the coloring.

ggplot(data = TD,
       aes(x = date, 
           y = value)) + 
  geom_line() + 
  scale_x_date(date_labels = "%d-%m-%Y", 
               breaks = date_breaks("2 day")) +
  theme(axis.text.x = element_text(angle = 45, 
                                   hjust = 1, 
                                   colour = c(rep("red", 10), rep("blue", 45))))

It is not a beautiful solution, but as far as I know the only one. It you don't want the x-axis scale to expand. Add expand = c(0, 0) to the scale_x_date function. Keep in mind you need to change to amount of red and blue again.

You first define breaks for your x-axis, one option is to use the date_break you have called. Once the breaks are defined, convert them into months and assign a colour for every month. Try the below:

library(ggplot2)
library(scales)
library(RColorBrewer)

today <- Sys.Date()
tm <- seq(0, 100, by = 1)
x <- today + tm
y <- rnorm(length(x))
TD<-data.frame(date=x, value=y)

BR = date_breaks(width="2 day")(range(TD$date))
MTHS = months(BR)
# if you need different years-months
#MTHS = sub("-[0-9]*$","",BR)
COLS = brewer.pal(length(unique(MTHS)),"Set1")
names(COLS) = unique(MTHS)

ggplot(data = TD, aes(x = date, y = value)) + 
  geom_line() + 
  scale_x_date(date_labels = "%d-%m-%Y", breaks = BR) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = COLS[MTHS]))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM