Cap. Rodgers
Cap. Rodgers

Reputation: 33

Creating a 2 line graph on left axis and a bar graph on right axis Octave

I'm having difficulty creating a 2 y axis graph in Octave. Currently I can make the 2 line graph. However, I haven't been able to find a function that will help me with my problem. I have tried using the plotyy function but I am not sure if you can use this function with two left side axis line graphs and one right side graph. Here is code I have written so far in my attempt.

labels = ["Data 1"; "Data 2"; "Data 3"; "Data 4"; "Data 5"]
y1 = [137, 15, 2, 3, 37]
y2 = [43, 1, 67, 97, 41]
x = [1, 2, 3, 4, 5]
y3 = [0, .2, .3, .104, .09]
z1 = plot(x, y1, y2) 
plot(x, y1, y2)
hold on
plot(x, y2)
xlabel("Version")
yyaxis left
ylabel("Y axis")
set(gca,'XTickLabel',labels)
yyaxis right
z = bar(x,y3)
z
yyaxis right
ylabel("Data")

Upvotes: 0

Views: 2044

Answers (1)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22255

While plotyy is the command to plot two normal plots using distinct left and right yaxes, I don't think you can do what you were trying to do with it. (i.e. mix two plots with a bar chart). However, what plotyy does is literally a simple case of overlaying two axes at the same position and making one 'see-through'. So you can use the same approach in general.

Here's your example above re-worked to achieve this (plus some extra bling):

x  = [1, 2, 3, 4, 5]; labels = ["Data 1"; "Data 2"; "Data 3"; "Data 4"; "Data 5"];
y1 = [137, 15, 2, 3, 37]; y2 = [43, 1, 67, 97, 41]; y3 = [0, .2, .3, .104, .09];

ax_left = axes('position', [0.15, 0.12, 0.7, 0.82]); % manually positioned
plot (x, y1, 'r-', 'linewidth', 3); hold on
plot (x, y2, 'g:', 'linewidth', 3); hold off
set (ax_left, ...
     'fontsize', 16, 'fontweight', 'bold', 'labelfontsizemultiplier', 1.2, ...
     'color', 'none', ...         % makes 'background' see-through
     'box', 'off', ...            % prevents left axis ticks in the right axis
     'xlim', [0, 6], 'ylim', [0, 150], 'xtick', x, 'xticklabel', labels);
xlabel('Version'); ylabel('Left Y-Axis');

ax_right = axes('position', [0.15, 0.12, 0.7, 0.82]); % same position as above
bar (x, y3, 0.5, 'facecolor', [0, 0.5, 1]);  % nice narrow light blue columns
set (ax_right, ...
     'fontsize', 16, 'fontweight', 'bold',  'labelfontsizemultiplier', 1.2, ...
     'yaxislocation', 'right', ...
     'ycolor', [0, 0.5, 1], ... % same nice light blue color as bar chart
     'box', 'off', 'xlim', [0, 6], 'ylim', [0, 0.35], 'xtick', []);
ylabel('Data');

% ensure axes are stacked in the order you want them to appear (bottom to top)
axes(ax_right);
axes(ax_left);

enter image description here

Upvotes: 0

Related Questions