How can I change the color of specific sections in a Line Chart in R Highchart?

Below is the code snippet along with the highchart chart:

library(tidyverse)
library(gapminder)
library(highchart)

highchart() %>%
  hc_add_series(
    data = gapminder %>% filter(country == 'Chile'),
    hcaes(x = year, y = pop),
    color = 'red',
    type = 'line'
  )

I want to change the color of the chart to blue for years above 1990.

The expected outcome is a chart displaying a red line from 1952 to 1990 and a blue line from 1990 to 2005.

I am looking for a solution using only one hc_add_series function.

Any assistance would be greatly appreciated!

Answer №1

Update

If you prefer using just one hc_add_series, consider utilizing zones in conjunction with a specified zoneAxis. Within the designated zone, define the desired value and color based on the range of your chosen zoneAxis, x or y. In this instance, it pertains to x, specifically pinpointing the year 1990. Below is an illustrative example:

library(tidyverse)
library(gapminder)
library(highcharter)

highchart() %>%
  hc_add_series(
    data = gapminder %>% filter(country == 'Chile'),
    hcaes(x = year, y = pop),
    type = 'line',
    zoneAxis = 'x',
    zones = list(list(value = 1990, color = 'red'), list(value = 1990, color = 'blue'))
  )

https://i.sstatic.net/oPQpB.png

Generated on 2022-10-07 utilizing reprex v2.0.2


You have the option to create two hc_add_series instances with distinct filter conditions. The issue might arise from the absence of data for the year 1990, so here's an alternative approach:

library(tidyverse)
library(gapminder)
library(highcharter)

highchart() %>%
  hc_add_series(
    data = gapminder %>% filter(country == 'Chile' & year <= 1990),
    hcaes(x = year, y = pop),
    color = 'red',
    type = 'line'
  ) %>%
  hc_add_series(
    data = gapminder %>% filter(country == 'Chile' & year > 1990),
    hcaes(x = year, y = pop),
    color = 'blue',
    type = 'line'
  )

https://i.sstatic.net/Pw4Tx.png


highchart() %>%
  hc_add_series(
    data = gapminder %>% filter(country == 'Chile' & year <= 1992),
    hcaes(x = year, y = pop),
    color = 'red',
    type = 'line'
  ) %>%
  hc_add_series(
    data = gapminder %>% filter(country == 'Chile' & year > 1991),
    hcaes(x = year, y = pop),
    color = 'blue',
    type = 'line'
  )

https://i.sstatic.net/IQ6OX.png

Generated on 2022-10-02 utilizing reprex v2.0.2

Answer №2

If you want to customize the colors of a series, you can use zones to define different color ranges for specific values.

Highcharts.chart('graph-container', {
    series: [{
        data: [-20, -10, 0, 10, 20, 30, 20, 20, 10, 0, -10],
        zones: [{
            value: 0,
            color: '#f7a35c'
        }, {
            value: 10,
            color: '#7cb5ec'
        }, {
            color: '#90ed7d'
        }]
    }]
});

Visit this link for more information on using zones in Highcharts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accordion checkbox with dynamic features

Currently, I am dynamically populating data into a jQuery accordion. My goal is to include a checkbox just before the <h2> text. <div id="checkbox"> <h2> <span> <input type="checkbox" class="mycheck" value="apple" / ...

Submitting forms with Ajax in IE(8)

Sample Google form Related spreadsheet I modified the original code to create two custom forms: First created form Second created form Both forms are functional on most browsers except for IE(8). Any idea why? First form: <!DOCTYPE html> <h ...

Utilizing React-map-gl in combination with either useContext or useState to update the viewport from a separate component

Lately, I've been struggling to understand how to use useContext and/or useState with React/Nextjs along with react-map-gl. In my project, I have a searchbox component that uses Formik and a map component from react-map-gl. What I'm trying to ach ...

Data binding in AngularJS allows for easy synchronization between the model and the view

I've been working on a simple AngularJS application that includes a form with two fields. However, I've run into an issue where I'm unable to read the values entered in these fields from my controller, as I keep getting 'undefined' ...

Updating the time and date format within an AngularJS application

I am receiving date and time data from the API and would like to adjust the format. The current format is "2016-05-12", "07:17:35". Desired format: 12-May-2016 7:30 PM: <table class="table"> <thead> <tr> <th& ...

jQuery: Modifying the Style of obj "th" Element

I am looking to update the style of my selection using jQuery. After using this module to retrieve all items, I have a list of cells with new coordinates. //cell list with new coordinates cl = Object {0-0: th, 0-1: th, 0-2: th, 0-3: th, 1-0: td…}, id = ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

Creating a dynamic word cloud in D3: Learn how to automatically adjust font sizes to prevent overflow and scale words to fit any screen size

I am currently utilizing Jason Davies' d3-cloud.js to create my word cloud, you can view it here 1. I'm encountering an issue where the words run out of space when the initial window size is too small. To address this, I have a function that cal ...

I'm wondering if affdex-sdk can be utilized in node.js to store emotion data in mongodb

Is it possible to utilize the affdex Javascript SDK with Node.js for saving emotion data to MongoDB? Can the emotion data collected on the frontend be passed to the backend (Node.js) for storage in MongoDB? The CameraDetector constructor requires four pa ...

Obtain item from JSON data structure

After querying my database, I receive a JSON object with the following structure: items = [ {"ID":1, "CODE":"code1", "DESCRIPTION":"abcd", "PRICE":100}, {"ID":2, "CODE":"code2", "DESCRIPTION":"efgh", "PRICE":100}, {"ID":3, "CODE":"code3", "DES ...

What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values ...

awaitMessages feature does not capture slash commands

In my development process, I have a file named botReady.js that is designed to run as soon as the bot becomes ready. In this file, there is a specific section dedicated to handling a bump bot in a designated channel obtained using the client.channels.fetch ...

What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line this.$store.commit('disconnect');, it throws a "this is undefined" error. Any suggestions on how to resolve this issue? store/index.js : export const state = () => ({ log: false, user: {token: null, id: null, u ...

Retrieving information from the logger to provide back to the web application

I'm almost there, but not quite. The logger is showing the search results, but I still can't get them to display on the web app. The search function works on the web app and the results show up in the logger. Any advice would be appreciated. Th ...

Exploring the world of web development with a mix of

var articles = [ {% for article in article_list %} {% if not forloop.first %},{% endif %} { title: "{{ article.title }}", slug: "{{ article.slug }}", content: "{{ article.content }}", auth ...

Three bizarre phenomena encountered when pushing mesh in JavaScript

Excuse my inexperience, I am quite new to javascript and THREE. In the code snippet below, I am attempting to add meshes to a list of objects: geometry = new THREE.BoxGeometry( 1, 50, 1 ); for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) { ...

Determine whether the textfield is a number or not upon losing focus

I'm seeking advice on implementing a feature using jQuery and JavaScript. I want to create a text field that, when something is inputted, will automatically add .00 at the end if it's only a number. However, if someone inputs something like 2.00, ...

Retrieve information from various HTTP GET requests prior to issuing a response

Looking for a solution with code that processes an array of data, sends HTTP GET requests for each item, and stores the returned data in a new array before running a specified callback method: function(handlePlayers, runCallback) { var result = []; ...

Dividing vector: Utilize the initial i-th element within a vector for creating an equivalent split

Looking to divide a vector into subvectors with minimal overlapping, which can be achieved using the r function. blocks <- function(len, ov, n) { starts <- unique(sort(c(seq(1, n, len), seq(len-ov+1, n, len)))) ends <- pmin(starts + len - 1, ...