Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6878347
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:42:45+00:00 2026-05-27T04:42:45+00:00

I’m an R/ggplot newbie. I would like to create a geom_line plot of a

  • 0

I’m an R/ggplot newbie. I would like to create a geom_line plot of a continuous variable time series and then add a layer composed of events. The continuous variable and its timestamps is stored in one data.frame, the events and their timestamps are stored in another data.frame.

What I would really like to do is something like the charts on finance.google.com. In those, the time series is stock-price and there are “flags” to indicate news-events. I’m not actually plotting finance stuff, but the type of graph is similar. I am trying to plot visualizations of log file data. Here’s an example of what I mean…

google chart with events

If advisable (?), I would like to use separate data.frames for each layer (one for continuous variable observations, another for events).

After some trial and error this is about as close as I can get. Here, I am using example data from data sets that come with ggplot. “economics” contains some time-series data that I’d like to plot and “presidential” contains a few events (presidential elections).

library(ggplot2)
data(presidential)
data(economics)

presidential <- presidential[-(1:3),]
yrng <- range(economics$unemploy)
ymin <- yrng[1]
ymax <- yrng[1] + 0.1*(yrng[2]-yrng[1])

p2 <- ggplot()
p2 <- p2 + geom_line(mapping=aes(x=date, y=unemploy), data=economics , size=3, alpha=0.5) 
p2 <- p2 + scale_x_date("time") +  scale_y_continuous(name="unemployed [1000's]")
p2 <- p2 + geom_segment(mapping=aes(x=start,y=ymin, xend=start, yend=ymax, colour=name), data=presidential, size=2, alpha=0.5)
p2 <- p2 + geom_point(mapping=aes(x=start,y=ymax, colour=name ), data=presidential, size=3) 
p2 <- p2 + geom_text(mapping=aes(x=start, y=ymax, label=name, angle=20, hjust=-0.1, vjust=0.1),size=6, data=presidential)
p2

my attempt

Questions:

  • This is OK for very sparse events, but if there’s a cluster of them (as often happens in a log file), it gets messy. Is there some technique I can use to neatly display a bunch of events occurring in a short time interval? I was thinking of position_jitter, but it was really hard for me to get this far. google charts stacks these event “flags” on top of each other if there’s a lot of them.

  • I actually don’t like sticking the event data in the same scale as the continuous measurement display. I would prefer to put it in a facet_grid. The problem is that the facets all must be sourced from the same data.frame (not sure if that’s true). If so, that also seems not ideal (or maybe I’m just trying to avoid using reshape?)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T04:42:46+00:00Added an answer on May 27, 2026 at 4:42 am

    As much as I like @JD Long’s answer, I’ll put one that is just in R/ggplot2.

    The approach is to create a second data set of events and to use that to determine positions. Starting with what @Angelo had:

    library(ggplot2)
    data(presidential)
    data(economics)
    

    Pull out the event (presidential) data, and transform it. Compute baseline and offset as fractions of the economic data it will be plotted with. Set the bottom (ymin) to the baseline. This is where the tricky part comes. We need to be able to stagger labels if they are too close together. So determine the spacing between adjacent labels (assumes that the events are sorted). If it is less than some amount (I picked about 4 years for this scale of data), then note that that label needs to be higher. But it has to be higher than the one after it, so use rle to get the length of TRUE‘s (that is, must be higher) and compute an offset vector using that (each string of TRUE must count down from its length to 2, the FALSEs are just at an offset of 1). Use this to determine the top of the bars (ymax).

    events <- presidential[-(1:3),]
    baseline = min(economics$unemploy)
    delta = 0.05 * diff(range(economics$unemploy))
    events$ymin = baseline
    events$timelapse = c(diff(events$start),Inf)
    events$bump = events$timelapse < 4*370 # ~4 years
    offsets <- rle(events$bump)
    events$offset <- unlist(mapply(function(l,v) {if(v){(l:1)+1}else{rep(1,l)}}, l=offsets$lengths, v=offsets$values, USE.NAMES=FALSE))
    events$ymax <- events$ymin + events$offset * delta
    

    Putting this together into a plot:

    ggplot() +
        geom_line(mapping=aes(x=date, y=unemploy), data=economics , size=3, alpha=0.5) +
        geom_segment(data = events, mapping=aes(x=start, y=ymin, xend=start, yend=ymax)) +
        geom_point(data = events, mapping=aes(x=start,y=ymax), size=3) +
        geom_text(data = events, mapping=aes(x=start, y=ymax, label=name), hjust=-0.1, vjust=0.1, size=6) +
        scale_x_date("time") +  
        scale_y_continuous(name="unemployed \[1000's\]")
    

    You could facet, but it is tricky with different scales. Another approach is composing two graphs. There is some extra fiddling that has to be done to make sure the plots have the same x-range, to make the labels all fit in the lower plot, and to eliminate the x axis in the upper plot.

    xrange = range(c(economics$date, events$start))
    
    p1 <- ggplot(data=economics, mapping=aes(x=date, y=unemploy)) +
        geom_line(size=3, alpha=0.5) +
        scale_x_date("", limits=xrange) +  
        scale_y_continuous(name="unemployed [1000's]") +
        opts(axis.text.x = theme_blank(), axis.title.x = theme_blank())
    
    ylims <- c(0, (max(events$offset)+1)*delta) + baseline
    p2 <- ggplot(data = events, mapping=aes(x=start)) +
        geom_segment(mapping=aes(y=ymin, xend=start, yend=ymax)) +
        geom_point(mapping=aes(y=ymax), size=3) +
        geom_text(mapping=aes(y=ymax, label=name), hjust=-0.1, vjust=0.1, size=6) +
        scale_x_date("time", limits=xrange) +
        scale_y_continuous("", breaks=NA, limits=ylims)
    
    #install.packages("ggExtra", repos="http://R-Forge.R-project.org")
    library(ggExtra)
    
    align.plots(p1, p2, heights=c(3,1))
    

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to count the length of a string with PHP. The string
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
Basically, what I'm trying to create is a page of div tags, each has
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.