简体   繁体   中英

How to manually create line types in ggplot?

I have the following dataframe, which I want to plot:

df = data.frame(
  a = 1:2,
  b = 1:2)

p = ggplot(df, aes(a,b)) 
p + geom_line()

在此处输入图像描述

which is fine, but I want to be able to set different sorts of line types, as I have several groups. I visit this website: http://www.sthda.com/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software#change-manually-the-appearance-of-lines . I tried

p + geom_line(linetype = 'dashed')

在此处输入图像描述

Yet I would like a way to build the line exactly as I want (ie, not from ready-to-use templates). For example, a line made of long lines and long blanks. Any idea?

You can specify how long you would like your on- and off-lines to be by providing your geom function with a hex string. From the docs:

# An example with hex strings, the string "33" specifies three units on followed
# by three off and "3313" specifies three units on followed by three off followed
# by one on and finally three off.
f + geom_line(linetype = "3313")

I think your best option is to use the aesthetic of geom_line .

You can customize them as much as you want, take a look at the documentation . Options include x,y,alpha,colour,group,l.netype,size .

You can also make your own geom , if you really want to build them yourself.

The solution is to supply a sequence of pairs of numbers to the argument l.netype in geom_line(). Specifically, in each pair, the first number specifies the length of the solid part of the line, and the second specifies the length of the blank part of the line. So for example, '11' implies one unit of line and one unit of blank. Similarly, '22' implies 2 units of solid line and 2 units of blank. Or, '48' implies 4 units of lines and 8 of blank.

df = data.frame(
  a = 1:2,
  b = 1:2)

p = ggplot(df, aes(a,b)) 
p + geom_line(linetype = '48')

在此处输入图像描述

But the line type can be much more elaborated. For example:

p + geom_line(linetype = '48')

Here, we made a line made of 4 units of lines, 8 blanks, 2 units of solid and 2 units of blanks.

在此处输入图像描述

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