Slightly separate overlapping lines on categorical variable line plot
Show older comments
I am attempting to create a line chart with a categorical y-axis and a numerical x-axis. I would like to separarate the blue and red line slightly above/below to be able to compare the two lines. The lines need to be close enough that they clearly belong to the corresponding name.
repex_table = table();
repex_table.name = string(["a", "b", "c"])';
repex_table.min1 = [1, 2, 3]';
repex_table.max1 = [5, 6, 7]';
repex_table.min2 = [4, 5, 6]';
repex_table.max2 = [9, 10, 11]';
% Create Figure
figure;
hold on;
for i=1:height(repex_table)
x = [repex_table(i,:).min1, repex_table(i,:).max1];
x2 = [repex_table(i,:).min2, repex_table(i,:).max2];
y = categorical([repex_table(i,:).name, repex_table(i,:).name]);
line(x, y, 'color', 'b')
line(x2, y, 'color', 'r')
end
hold off;

Answers (1)
Walter Roberson
on 23 May 2023
0 votes
You do not have many options:
- you could convert the categorical y to numeric so that you could add numeric offsets
- you can use axes() to add a second axes to draw the other line in, perhaps making the second one numeric
- you can use yyaxis to add a second axes to draw the other line in, perhaps making the second one numeric
- you could create a lot of categories in your categoricals, like a, a_05 a_10 a_15 a_20 and so on, and give the second y line the "next" category up from what it would normally be, and use yticks() to control which ones are labeled on the axes
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!