R:在ggplot2中编辑y轴:突出显示字符

时间:2015-09-08 07:01:31

标签: r ggplot2

我正在使用ggplot2并需要编辑y轴的比例。更确切地说,我需要为值设置黄色背景,就像用标记针突出显示一样。我尝试用

这样做
from lxml import html
import requests
import csv

page = requests.get('http://www.wintergreenfund.com/reports/top-ten/')
tree = html.fromstring(page.text)

csvrows = []
for rows in tree.xpath('//*[@id="colLeft"]//table//tr'):
    csvrows.append([rows.xpath('./td[1]/text()'),rows.xpath('./td[2]/text()')])
print csvrows
print 'Input the csv file'
csvfile = raw_input("> ")
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(['Name','Value']) #substitute as appropriate.
    writer.writerows(csvrows)

但是,我可以只编辑文本颜色,但不能编辑其背景。

这是我的代码的简单版本:

+ theme(axis.text.y=element_text(colour="#00669C"))

最后,我的比例看起来应该是这样的:

http://www.directupload.net/file/d/4104/9au5flxu_png.htm
enter image description here

1 个答案:

答案 0 :(得分:1)

很可能有一种更简洁的方法来覆盖轴凹凸;但是这里有一种方法可以创建填充文本的矩形,并使用annotation_custom()

定位它们(​​使用粗略的手动调整)

原图

p <- ggplot(df, aes(x=Date, y=x1)) + geom_line() +
             scale_y_continuous(limits=c(5, 40), expand = c(0, 0)) +
             scale_x_date(labels = date_format("%b. %y")) 

提取y轴标签和fontsize

g <- ggplotGrob(p)  
pth <- g$grobs[[grep("axis-l", g$layout$name)]]$children[[2]]$grobs[[1]]
ylb <- as.numeric(pth$label)
fs <- pth$gp$fontsize

# Function to create yellow box with blue text inside
box_fun <- function(txt, fs, col="blue", fill="yellow", 
                            hadj=unit(0.05, "npc"), wadj=unit(0.2, "npc"))
            {
             txtG <- textGrob(txt, just="centre", gp=gpar(fontsize=fs, col=col))
             h <- unit.c(grobHeight(txtG) + hadj)
             w <- unit.c(grobWidth(txtG) + wadj)
             grobTree(rectGrob(height=h, width=w, 
                                gp=gpar(col=fill, fill=fill)), txtG )
            }

# Create seperate grobs for each axis label text
box_g <- Map(box_fun, ylb, fs)

# Add to plot
# Used manual adjustment to get the x and y positions          
newp <- p + lapply(seq(box_g), function(i) 
             annotation_custom(box_g[[i]], 
                xmin=as.numeric(min(Date))-300, xmax=as.numeric(min(Date))-100, 
                ymin=(ylb-5)[i], ymax=(ylb+5)[i])) 


gp <- ggplotGrob(newp + theme(axis.text.y=element_blank()) )
gp$layout$clip[gp$layout$name=="panel"] <- "off"
grid.newpage()
grid.draw(gp)

给予

enter image description here