Labeling data points in plotyy

2 次查看(过去 30 天)
I need to plot two bar series in different scales and thus I am using the plotyy function as in the example below. I'm trying to show the values of the data points I plot with the bar function. The issue is that the labels I draw are not very well positioned for the series in the second axis (please see the example)
My question is: How can I make the text function correctly draw the text for the data points of the series in the right axis?
Thanks in advance
Just in case, I cannot put the first series in the second axes, and the second series in the first axes, the solution needs not to depend on such an order.
%%%%%%%%%%%%%%%%%
x = 15;
y = {rand(x, 1) * 100; (-0:(0.8)/(x-1):0.8)'};
fn1 = @(x, y) bar(x, y, 0.3, 'FaceColor', 'blue');
fn2 = @(x, y) bar(x, y, 0.3, 'FaceColor', 'red');
figure;
[ax, hbar1, hbar2] = plotyy( [1:x]-1, y{1}, [1:x]+1, y{2}, fn1, fn2);
hbars = [hbar1, hbar2];
angle = 67.5;
for i=1:length(hbars)
hbar = hbars(i);
x = get(get(hbar,'children'), 'xdata');
rot = angle;
while rot>360, rot=rot-360; end
while rot<0, rot=rot+360; end
if rot>=180, strDir='right'; else, strDir='left'; end
caDataLabels = strread(sprintf(' %.3g\n', y{i}), '%s', 'delimiter', sprintf('\n'), 'whitespace', '');
th=text(mean(x,1)', y{i}, caDataLabels, 'HorizontalAlignment', strDir, 'rotation', rot, 'FontSize', 8, 'VerticalAlignment', 'middle');
end

采纳的回答

Jiro Doke
Jiro Doke 2012-2-27
You can specify the axes in which to place the text. For example, specify ax(2) for the right axes.
Notice below, I specified the Parent property for the text command. Also, to distinguish the labels, I specified the colors.
clr = {'blue', 'red'};
x = 15;
y = {rand(x, 1) * 100; (-0:(0.8)/(x-1):0.8)'};
fn1 = @(x, y) bar(x, y, 0.3, 'FaceColor', clr{1});
fn2 = @(x, y) bar(x, y, 0.3, 'FaceColor', clr{2});
figure;
[ax, hbar1, hbar2] = plotyy( [1:x]-1, y{1}, [1:x]+1, y{2}, fn1, fn2);
hbars = [hbar1, hbar2];
angle = 67.5;
for i=1:length(hbars)
hbar = hbars(i);
x = get(get(hbar,'children'), 'xdata');
rot = angle;
while rot>360, rot=rot-360; end
while rot<0, rot=rot+360; end
if rot>=180, strDir='right'; else, strDir='left'; end
caDataLabels = strread(sprintf(' %.3g\n', y{i}), '%s', ...
'delimiter', sprintf('\n'), 'whitespace', '');
th=text(mean(x,1)', y{i}, caDataLabels, 'Parent', ax(i), ...
'Color', clr{i}, 'HorizontalAlignment', strDir, ...
'rotation', rot, 'FontSize', 8, 'VerticalAlignment', 'middle');
end

更多回答(1 个)

Mark
Mark 2012-2-27
For reference, here's another solution I just found:
%%Set the current axes
set(gcf(), 'CurrentAxes', ax(i));
%%Draw the text
th=text(mean(x,1)', y{i}, caDataLabels, 'HorizontalAlignment', strDir, 'rotation', rot, 'FontSize', 8, 'VerticalAlignment', 'middle');

类别

Help CenterFile Exchange 中查找有关 Axis Labels 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by