简体   繁体   中英

Stata: Two way plot, add text to second line using coordinates of the second axis

I have a plot of a histogram, to which I would like to add the median. I cannot use xline() because the line falls behind the histogram, rather than on top of it. To fix this, I am using scatteri with coordinates.

Because I do not know the height of the histogram beforehand, I set the scatteri plot to use a separate y-axis, which I have hidden. However, I cannot seem to add text to this line using the second y-axis coordinates (it instead uses the first y-axis coordinates, even though the object it is labeling is on the second y-axis). Here is an example of my issue:

sysuse auto

sum mpg, d
local median = r(p50)
twoway hist mpg, start(10) width(5) || ///
    scatteri 0 `median' 1 `median', recast(line) yaxis(2) ///
    ylabel(none, axis(2)) ytitle("", axis(2)) lc(red) ///
    text(0.08 `median' `"median = $`=string(`median',"%6.2f")'"', ///
        color(red) placement(se)) ///
    legend(off)

This produces the desired graph (for the most part*):

在此处输入图像描述

At issue is that I do not know the height of the histogram beforehand. This is the reason I used the second y-axis in the first place. Instead of "0.08" which gets my text into the correct location, I would like to use "1", as this is the maximum value of the second y-axis. The corresponding lines would instead be:

text(1 `median' `"median = $`=string(`median',"%6.2f")'"', ///
    color(red) placement(se)) ///

Of course, I could manually determine this value for the histogram (as I did in this example), but I plan to create a set of these graphs via a loop, such that there are a dozen or so panels. It seems better to be able to attach the text to the line using the second y-axis gridpoints.

I have tried adding axis(2) to the text box as an additional argument, but this option is apparently not allowed.

*A second, minor question is that I do not understand why the x-axis gets an elipsis (...) when I add the scatteri plot. I would like to remove this.

Doing exactly what you did is at best awkward, because you need two passes, one to find out how high the density gets and another to draw the graph as you want it.

I would tend to use transparent bars and a custom axis label to show the same information. In this example, fortuitously the median coincides with a bar edge, which presumably isn't out of the question for your real data. Any way, I changed the bar set-up.

sysuse auto, clear
su mpg, detail
blcolor(black) xline(20) xaxis(1 2) xla(20 "median 20", axis(2))

在此处输入图像描述

Naturally, you could remove or otherwise change the axis title that appears at the top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM