Plot line in different colors above versus below zeroPlot a line chart with conditional colors depending on valuesFilling area under curve based on valueHow to keep only break in colors to septate values above zero from those below zero?plotting mean of variable versus matrix of conditions in R using ggplot2How to make line width and text width bigger in R ternary plot?R line graphs, values outside plot areaSolve best fit polynomial and plot drop-down linesCount Points in R scatter plot above/below thresholdHow to plot the difference between two ggplot density distributions?How to plot columns above and below data points in ggplot2Plot the color and line type in the same legendUnique color ramp using factor with positive values below and above 0 using ggplot2

The Passive Wisdom (Perception) score of my character on D&D Beyond seems too high

How do you deal with an abrupt change in personality for a protagonist?

What is a subpixel in Super Mario Bros, and how does it relate to wall clipping?

Uses of T extends U?

How does an ARM MCU run faster than the external crystal?

How to prevent bad sectors?

Is there an explanation for Austria's Freedom Party virtually retaining its vote share despite recent scandal?

Where do I put diamond mines on my map?

Crossword gone overboard

File globbing pattern, !(*example), behaves differently in bash script than it does in bash shell

Infinitely many hats

Have I been doing real analysis incorrectly?

How does apt-get works (in details)?

If a person had control of every single cell of their body, would they be able to transform into another creature?

Future enhancements for the finite element method

I think I may have violated academic integrity last year - what should I do?

Do firearms count as ranged weapons?

Employer demanding to see degree after poor code review

If a massive object like Jupiter flew past the Earth how close would it need to come to pull people off of the surface?

What F1 in name of seeds/varieties means?

How to capture more stars?

How to extract lower and upper bound in numeric format from a confidence interval string?

What are the benefits of cryosleep?

Is it ok to put a subplot to a story that is never meant to contribute to the development of the main plot?



Plot line in different colors above versus below zero


Plot a line chart with conditional colors depending on valuesFilling area under curve based on valueHow to keep only break in colors to septate values above zero from those below zero?plotting mean of variable versus matrix of conditions in R using ggplot2How to make line width and text width bigger in R ternary plot?R line graphs, values outside plot areaSolve best fit polynomial and plot drop-down linesCount Points in R scatter plot above/below thresholdHow to plot the difference between two ggplot density distributions?How to plot columns above and below data points in ggplot2Plot the color and line type in the same legendUnique color ramp using factor with positive values below and above 0 using ggplot2






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I'd like the plotted line to be blue for values above zero and red for values below zero.



Sample data:



dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2)
abline(h = 0, col = "grey")


Result:



image of resulting plot



Expected result:



image of expected resulting plot



I do not want to use ggplot2 and would prefer a solution in base R.










share|improve this question






















  • Possible duplicate of Plot a line chart with conditional colors depending on values

    – Sonny
    Mar 24 at 8:49

















2















I'd like the plotted line to be blue for values above zero and red for values below zero.



Sample data:



dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2)
abline(h = 0, col = "grey")


Result:



image of resulting plot



Expected result:



image of expected resulting plot



I do not want to use ggplot2 and would prefer a solution in base R.










share|improve this question






















  • Possible duplicate of Plot a line chart with conditional colors depending on values

    – Sonny
    Mar 24 at 8:49













2












2








2








I'd like the plotted line to be blue for values above zero and red for values below zero.



Sample data:



dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2)
abline(h = 0, col = "grey")


Result:



image of resulting plot



Expected result:



image of expected resulting plot



I do not want to use ggplot2 and would prefer a solution in base R.










share|improve this question














I'd like the plotted line to be blue for values above zero and red for values below zero.



Sample data:



dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2)
abline(h = 0, col = "grey")


Result:



image of resulting plot



Expected result:



image of expected resulting plot



I do not want to use ggplot2 and would prefer a solution in base R.







r plot colors






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 8:21







user10915156



















  • Possible duplicate of Plot a line chart with conditional colors depending on values

    – Sonny
    Mar 24 at 8:49

















  • Possible duplicate of Plot a line chart with conditional colors depending on values

    – Sonny
    Mar 24 at 8:49
















Possible duplicate of Plot a line chart with conditional colors depending on values

– Sonny
Mar 24 at 8:49





Possible duplicate of Plot a line chart with conditional colors depending on values

– Sonny
Mar 24 at 8:49












3 Answers
3






active

oldest

votes


















1














Following this answer [as @Sonny suggested in the comment], you can do this using clip:



dat <- data.frame(u = 1:10,
v = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2, col = "blue")
clip(x1 = min(dat$u),
x2 = max(dat$u),
y1 = min(dat$v),
y2 = 0)
lines(dat, lwd = 2, col = "red")
abline(h = 0, col = "grey")




Created on 2019-03-24 by the reprex package (v0.2.1)






share|improve this answer


















  • 1





    If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

    – Ronak Shah
    Mar 24 at 9:26











  • @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

    – yarnabrina
    Mar 24 at 9:58


















1














I am now using clplot() from the plotrix package:



dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
library(plotrix)
clplot(dat[, 1], dat[, 2], levels = c(0), cols = c("red", "blue"), lwd = 2)


enter image description here






share|improve this answer






























    0














    There is a very flexible solution from @Kohske / @beroe around, which can also be adapted on lines.



    The method is that you estimate nullities.



    dat.add <- do.call(rbind, 
    sapply(1:(nrow(dat) - 1), function(i)
    f <- lm(x ~ y, dat[i:(i + 1), ])
    if (f$qr$rank < 2) return(NULL)
    r <- predict(f, newdata=data.frame(y=0))
    if(dat[i, ]$x < r & r < dat[i + 1, ]$x)
    return(data.frame(x=r, y=0))
    else return(NULL)
    )
    )


    Merge the nullites to your original data frame.



    dat <- merge(dat, dat.add, all=TRUE)


    Then do an empty plot and add segmented lines.



    plot(dat, lwd = 2, type="n")
    lines(dat[dat$y >= 0, ], col="blue")
    lines(dat[dat$y <= 0, ], col="red")
    abline(h = 0, col = "grey")


    Result



    enter image description here



    Note, that the lines are not interrupted on the zero line, but abline at 0 hides this fact so we shouldn't care much in this case.



    Data



    dat <- structure(list(x = 1:10, y = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 
    3)), class = "data.frame", row.names = c(NA, -10L))





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321886%2fplot-line-in-different-colors-above-versus-below-zero%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown
























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Following this answer [as @Sonny suggested in the comment], you can do this using clip:



      dat <- data.frame(u = 1:10,
      v = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
      plot(dat, type = "l", lwd = 2, col = "blue")
      clip(x1 = min(dat$u),
      x2 = max(dat$u),
      y1 = min(dat$v),
      y2 = 0)
      lines(dat, lwd = 2, col = "red")
      abline(h = 0, col = "grey")




      Created on 2019-03-24 by the reprex package (v0.2.1)






      share|improve this answer


















      • 1





        If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

        – Ronak Shah
        Mar 24 at 9:26











      • @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

        – yarnabrina
        Mar 24 at 9:58















      1














      Following this answer [as @Sonny suggested in the comment], you can do this using clip:



      dat <- data.frame(u = 1:10,
      v = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
      plot(dat, type = "l", lwd = 2, col = "blue")
      clip(x1 = min(dat$u),
      x2 = max(dat$u),
      y1 = min(dat$v),
      y2 = 0)
      lines(dat, lwd = 2, col = "red")
      abline(h = 0, col = "grey")




      Created on 2019-03-24 by the reprex package (v0.2.1)






      share|improve this answer


















      • 1





        If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

        – Ronak Shah
        Mar 24 at 9:26











      • @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

        – yarnabrina
        Mar 24 at 9:58













      1












      1








      1







      Following this answer [as @Sonny suggested in the comment], you can do this using clip:



      dat <- data.frame(u = 1:10,
      v = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
      plot(dat, type = "l", lwd = 2, col = "blue")
      clip(x1 = min(dat$u),
      x2 = max(dat$u),
      y1 = min(dat$v),
      y2 = 0)
      lines(dat, lwd = 2, col = "red")
      abline(h = 0, col = "grey")




      Created on 2019-03-24 by the reprex package (v0.2.1)






      share|improve this answer













      Following this answer [as @Sonny suggested in the comment], you can do this using clip:



      dat <- data.frame(u = 1:10,
      v = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
      plot(dat, type = "l", lwd = 2, col = "blue")
      clip(x1 = min(dat$u),
      x2 = max(dat$u),
      y1 = min(dat$v),
      y2 = 0)
      lines(dat, lwd = 2, col = "red")
      abline(h = 0, col = "grey")




      Created on 2019-03-24 by the reprex package (v0.2.1)







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 24 at 9:00









      yarnabrinayarnabrina

      640112




      640112







      • 1





        If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

        – Ronak Shah
        Mar 24 at 9:26











      • @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

        – yarnabrina
        Mar 24 at 9:58












      • 1





        If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

        – Ronak Shah
        Mar 24 at 9:26











      • @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

        – yarnabrina
        Mar 24 at 9:58







      1




      1





      If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

      – Ronak Shah
      Mar 24 at 9:26





      If you know this question has been asked before and is a duplicate you should not answer it in that case and should vote to close it as duplicate.

      – Ronak Shah
      Mar 24 at 9:26













      @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

      – yarnabrina
      Mar 24 at 9:58





      @RonakShah Thanks for letting me know. I didn't know that. I can't see any vote option, so possibly I need more reputation for that.

      – yarnabrina
      Mar 24 at 9:58













      1














      I am now using clplot() from the plotrix package:



      dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
      library(plotrix)
      clplot(dat[, 1], dat[, 2], levels = c(0), cols = c("red", "blue"), lwd = 2)


      enter image description here






      share|improve this answer



























        1














        I am now using clplot() from the plotrix package:



        dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
        library(plotrix)
        clplot(dat[, 1], dat[, 2], levels = c(0), cols = c("red", "blue"), lwd = 2)


        enter image description here






        share|improve this answer

























          1












          1








          1







          I am now using clplot() from the plotrix package:



          dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
          library(plotrix)
          clplot(dat[, 1], dat[, 2], levels = c(0), cols = c("red", "blue"), lwd = 2)


          enter image description here






          share|improve this answer













          I am now using clplot() from the plotrix package:



          dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
          library(plotrix)
          clplot(dat[, 1], dat[, 2], levels = c(0), cols = c("red", "blue"), lwd = 2)


          enter image description here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 9:03







          user10915156




























              0














              There is a very flexible solution from @Kohske / @beroe around, which can also be adapted on lines.



              The method is that you estimate nullities.



              dat.add <- do.call(rbind, 
              sapply(1:(nrow(dat) - 1), function(i)
              f <- lm(x ~ y, dat[i:(i + 1), ])
              if (f$qr$rank < 2) return(NULL)
              r <- predict(f, newdata=data.frame(y=0))
              if(dat[i, ]$x < r & r < dat[i + 1, ]$x)
              return(data.frame(x=r, y=0))
              else return(NULL)
              )
              )


              Merge the nullites to your original data frame.



              dat <- merge(dat, dat.add, all=TRUE)


              Then do an empty plot and add segmented lines.



              plot(dat, lwd = 2, type="n")
              lines(dat[dat$y >= 0, ], col="blue")
              lines(dat[dat$y <= 0, ], col="red")
              abline(h = 0, col = "grey")


              Result



              enter image description here



              Note, that the lines are not interrupted on the zero line, but abline at 0 hides this fact so we shouldn't care much in this case.



              Data



              dat <- structure(list(x = 1:10, y = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 
              3)), class = "data.frame", row.names = c(NA, -10L))





              share|improve this answer



























                0














                There is a very flexible solution from @Kohske / @beroe around, which can also be adapted on lines.



                The method is that you estimate nullities.



                dat.add <- do.call(rbind, 
                sapply(1:(nrow(dat) - 1), function(i)
                f <- lm(x ~ y, dat[i:(i + 1), ])
                if (f$qr$rank < 2) return(NULL)
                r <- predict(f, newdata=data.frame(y=0))
                if(dat[i, ]$x < r & r < dat[i + 1, ]$x)
                return(data.frame(x=r, y=0))
                else return(NULL)
                )
                )


                Merge the nullites to your original data frame.



                dat <- merge(dat, dat.add, all=TRUE)


                Then do an empty plot and add segmented lines.



                plot(dat, lwd = 2, type="n")
                lines(dat[dat$y >= 0, ], col="blue")
                lines(dat[dat$y <= 0, ], col="red")
                abline(h = 0, col = "grey")


                Result



                enter image description here



                Note, that the lines are not interrupted on the zero line, but abline at 0 hides this fact so we shouldn't care much in this case.



                Data



                dat <- structure(list(x = 1:10, y = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 
                3)), class = "data.frame", row.names = c(NA, -10L))





                share|improve this answer

























                  0












                  0








                  0







                  There is a very flexible solution from @Kohske / @beroe around, which can also be adapted on lines.



                  The method is that you estimate nullities.



                  dat.add <- do.call(rbind, 
                  sapply(1:(nrow(dat) - 1), function(i)
                  f <- lm(x ~ y, dat[i:(i + 1), ])
                  if (f$qr$rank < 2) return(NULL)
                  r <- predict(f, newdata=data.frame(y=0))
                  if(dat[i, ]$x < r & r < dat[i + 1, ]$x)
                  return(data.frame(x=r, y=0))
                  else return(NULL)
                  )
                  )


                  Merge the nullites to your original data frame.



                  dat <- merge(dat, dat.add, all=TRUE)


                  Then do an empty plot and add segmented lines.



                  plot(dat, lwd = 2, type="n")
                  lines(dat[dat$y >= 0, ], col="blue")
                  lines(dat[dat$y <= 0, ], col="red")
                  abline(h = 0, col = "grey")


                  Result



                  enter image description here



                  Note, that the lines are not interrupted on the zero line, but abline at 0 hides this fact so we shouldn't care much in this case.



                  Data



                  dat <- structure(list(x = 1:10, y = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 
                  3)), class = "data.frame", row.names = c(NA, -10L))





                  share|improve this answer













                  There is a very flexible solution from @Kohske / @beroe around, which can also be adapted on lines.



                  The method is that you estimate nullities.



                  dat.add <- do.call(rbind, 
                  sapply(1:(nrow(dat) - 1), function(i)
                  f <- lm(x ~ y, dat[i:(i + 1), ])
                  if (f$qr$rank < 2) return(NULL)
                  r <- predict(f, newdata=data.frame(y=0))
                  if(dat[i, ]$x < r & r < dat[i + 1, ]$x)
                  return(data.frame(x=r, y=0))
                  else return(NULL)
                  )
                  )


                  Merge the nullites to your original data frame.



                  dat <- merge(dat, dat.add, all=TRUE)


                  Then do an empty plot and add segmented lines.



                  plot(dat, lwd = 2, type="n")
                  lines(dat[dat$y >= 0, ], col="blue")
                  lines(dat[dat$y <= 0, ], col="red")
                  abline(h = 0, col = "grey")


                  Result



                  enter image description here



                  Note, that the lines are not interrupted on the zero line, but abline at 0 hides this fact so we shouldn't care much in this case.



                  Data



                  dat <- structure(list(x = 1:10, y = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 
                  3)), class = "data.frame", row.names = c(NA, -10L))






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 at 9:00









                  jay.sfjay.sf

                  8,16032043




                  8,16032043



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321886%2fplot-line-in-different-colors-above-versus-below-zero%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해