How to add units on the y-axis in a chart?

Description

Hi everyone, I would like to add a unit to the y-axis. Is it possible?

What MCU/Processor/Board and compiler are you using?

ESP32

What LVGL version are you using?

8.3.4

What do you want to achieve?

I want to label the y-axis with different units. Like the x-axis in the picture.

What have you tried so far?

The x-axis I have already managed to label with an event_cb, as in the chart example. I tried the same way as in the chart example, but it didn’t work.

Screenshot

Code

static void draw_event_cb(lv_event_t * e)
{
    lv_obj_draw_part_dsc_t * dsc = lv_event_get_draw_part_dsc(e);
    if(!lv_obj_draw_part_check_type(dsc, &lv_chart_class, LV_CHART_DRAW_PART_TICK_LABEL)) return;


    if(dsc->id == LV_CHART_AXIS_PRIMARY_Y && dsc->text) {
        const char * voltage[] = {"0V", "20V", "40V", "60V", "80V", "100V"};
        lv_snprintf(dsc->text, dsc->text_length, "%s", voltage[dsc->value]);
    }
}

What puzzles me, how did you manage to label the x-axis, as I don’t see the code for it.

Your code for labeling the y-axis is wrong.
If you have the tick values of 0, 20, 40… that means the dsc->value is 0, 20, 40…
That means you want to print voltage[0], voltage[20], voltage[40] …
Which is of course wrong, as you only have voltage[0…5].

As you just want to add a V to the ticks value, just do the following:

lv_snprintf (dsc->text, dsc->text_length, "%dV", dsc->value);
1 Like

Thank you robekras
This is exactly what I was looking for. This is how my chart looks now:

y-axis

 static void draw_event_cb_chart_y_axis(lv_event_t * e)
 {
  lv_obj_draw_part_dsc_t * dsc = lv_event_get_draw_part_dsc(e);
  if(!lv_obj_draw_part_check_type(dsc, &lv_chart_class, LV_CHART_DRAW_PART_TICK_LABEL)) return;

  if(0 == lv_dropdown_get_selected(dd_values))
  {
    if(dsc->id == LV_CHART_AXIS_PRIMARY_Y && dsc->text) {
    lv_snprintf (dsc->text, dsc->text_length, "%d V", dsc->value);
    }
    lv_chart_set_axis_tick(chart_values, LV_CHART_AXIS_PRIMARY_Y, 10, 5, 7, 2, true, 60);
  }

x-axis

static void draw_event_cb_chart_x_axis(lv_event_t * e)
{
  lv_obj_draw_part_dsc_t * dsc = lv_event_get_draw_part_dsc(e);
  if(!lv_obj_draw_part_check_type(dsc, &lv_chart_class, LV_CHART_DRAW_PART_TICK_LABEL)) return;

  if(0 == lv_dropdown_get_selected(dd_times))
  {
    const char *month[] = {"60 s", "50 s", "40 s", "30 s", "20 s", "10 s","0 s"};
    if(dsc->id == LV_CHART_AXIS_PRIMARY_X && dsc->text) {
    lv_snprintf(dsc->text, dsc->text_length, "%s", month[dsc->value]);
    }
    lv_chart_set_axis_tick(chart_values, LV_CHART_AXIS_PRIMARY_X, 10, 5, 7, 2, true, 40);
  }