关于Frame考古器物绘图pdf问题

java绘图问题_百度知道
java绘图问题
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.WindowA
public class Draw1{
public static final int YES_NO_OPTION = 0;
public static void main(String[] args){
DrawFrame drawF...
我有更好的答案
你这个主要是布局管理器太过混乱,窗口大小定义不当class&DrawPanel&extends&JPanel{你的public&void&paintComponent(Graphics&g){是在DrawPanel区域内执行的结果你直接&add(jp);&&&&&&&&add(controlPane,BorderLayout.NORTH);一、没有对DrawPanel进行布局管理器管理二、直接调用add()方法,覆盖了你的作图区域三、建议你引用ActionListener接口,继承只能继承一个,接口则无此限制四、修改窗口大小,以配合程序五、附赠你一段使窗口居中显示的代码import&java.awt.*;import&javax.swing.*;import&javax.swing.border.Bimport&java.awt.event.*;public&class&Draw1{&&public&static&final&int&YES_NO_OPTION&=&0;&&public&static&void&main(String[]&args){&&&&DrawFrame&drawFrame=new&DrawFrame();&&&&drawFrame.addWindowListener(new&WindowAdapter(){&&&&&&public&void&windowClosing(WindowEvent&e){&&&&&&&&int&result=JOptionPane.showConfirmDialog(null,&&确认退出&,null,YES_NO_OPTION);&&&&&&&&if(result==JOptionPane.YES_OPTION)&&&& &&System.exit(0);&&&&&&&&else&&&&&&&&&&&&&&&&}&&&&});&&&&drawFrame.setVisible(true);&&&&drawFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);&&}}class&DrawFrame&extends&JFrame{ Dimension& Toolkit&toolkit&=&Toolkit.getDefaultToolkit();&&JPanel&jp1=new&DrawPanel();&&public&DrawFrame(){&&&&setLayout(new&BorderLayout());&&&&setSize(300,400);&&&&scrnsize&=&toolkit.getScreenSize(); setLocation(scrnsize.width&/&2&-&getWidth()&/&2,
scrnsize.height&/&2&-&getHeight()&/&2);&&&&setTitle(&123&);&&&&add(jp1);&&&&}&}class&DrawPanel&extends&JPanel&implements&ActionListener{&&enum&Flag{STRING,RECT,CIRCLE};&&Flag&&&private&JPanel&total=new&JPanel();&&private&JPanel&jp=new&JPanel();&&private&JPanel&controlPane=new&JPanel();&&private&ButtonGroup&buttonGroup=new&ButtonGroup();&&&&private&JButton&yellow=new&JButton(&yellow&);&&private&JButton&red=new&JButton(&red&);&&private&JRadioButton&a=&new&JRadioButton(&String&,false);&&private&JRadioButton&b=&new&JRadioButton(&Rect&,false);&&private&JRadioButton&c=&new&JRadioButton(&circle&,false);&&public&DrawPanel(){&&&&&&&&&jp.setLayout(new&GridLayout(1,2));&&&&jp.add(yellow);&&&&yellow.addActionListener(this);&&&&jp.add(red);&&&&red.addActionListener(this);&&&&controlPane.add(a);&&&&controlPane.add(b);&&&&controlPane.add(c);&&&&buttonGroup.add(a);&&&&a.addActionListener(this);&&&&buttonGroup.add(b);&&&&b.addActionListener(this);&&&&buttonGroup.add(c);&&&&c.addActionListener(this);&&&&this.setLayout(&new&BorderLayout());&&&&total.setLayout(new&BorderLayout());&&&&total.add(jp,BorderLayout.NORTH);&&&&total.add(controlPane,BorderLayout.SOUTH);&&&&//add(jp,BorderLayout.SOUTH);&&&&&&&&//add(controlPane,BorderLayout.SOUTH);&&&&this.add(total,BorderLayout.SOUTH);&&&}//事件监听&&&&public&void&actionPerformed(ActionEvent&e){&&&&&&&if(e.getSource()==a)&&&&&&&&flag=Flag.STRING;&&&&&&&&&if(e.getSource()==b)&&&&&&&&flag=Flag.RECT;&&&&&&&if(e.getSource()==c)&&&&&&&&&flag=Flag.CIRCLE;&&&&&&&if(e.getSource()==yellow)&&&&&&&&&this.setBackground(Color.YELLOW);&&&&&&&if(e.getSource()==red)&&&&&&&&&this.setBackground(Color.RED);&&&&}&&&public&void&paintComponent(Graphics&g){&&&&&&super.paintComponent(g);&&&&&&if(flag==Flag.STRING)&&&&&&&&g.drawString(&abc&,100,50);&&&&&&&if(flag==Flag.RECT)&&&&&&&&g.fillRect(20,20,130,140);&&&&&&if(flag==Flag.CIRCLE)&&&&&&&g.fillOval(20,20,150,210);&&&&&&}}
采纳率:66%
来自团队:
//事件监听
以下就是把强制转换类型去掉 不过貌似你其他地方有问题
ActionListener actionListener=new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource()==a)
flag=Flag.STRING;
if(e.getSource()==b)
flag=Flag.RECT;
if(e.getSource()==c)
flag=Flag.CIRCLE;
if(e.getSource()==yellow)
jp.setBackground(Color.YELLOW);
if(e.getSource()==red)
jp.setBackground(Color.RED);
为您推荐:
其他类似问题
java的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。模拟画图-_百度文库
您的浏览器Javascript被禁用,需开启后体验完整功能,
享专业文档下载特权
&赠共享文档下载特权
&10W篇文档免费专享
&每天抽奖多种福利
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
阅读已结束,下载本文需要
想免费下载本文?
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
加入VIP
还剩29页未读,
定制HR最喜欢的简历
你可能喜欢博客分类:
原帖地址:http://www.cnblogs.com/lijianglidedaxia/archive//3113213.html  近期,公司的一个项目是采用华迈SDK来做一套C/S架构的监控中心。自己犯了两个低级错误,写出来看看有多少朋友平时跟我一样没注意,哈哈。
  第一个错误是这样出现的:在最初的几个版本中比较顺利。于是有点飘飘然,连续提交了好几个版本都没有进行全面测试。直到一个完成得差不多的版本出现后,来了一次全面的测试。这个时候发现,居然主界面显示不正常。找了好久原因没找到,只好回退到之前最初几个正常的版本,然后建立了个分支专门来排除此问题。一个一个版本的合并,一个一个文件的差异对比,最终定位到一个版本中原来把CXXX::OnPaint()中的CPaintDC dc(this);写成了CClientDC dc(this);
  下面是错误分析。
  《Windows 程序设计》里曾经说过,在WM_PAINT中一定要成对使用BeginPaint跟EndPaint。否则程序会不停产生WM_PAINT消息。而MFC的CPaintDC的构造与析构中封装了BeginPaint及EndPaint。而CClientDC则没有,所以在OnPaint中使用CClientDC当然是不行的。惭愧啊,惭愧。一时疏忽浪费我整整一个下午找这个BUG。
  第二个错误更加惭愧了。直接看码:
void CDxHMContainer::OnPaint(){
CPaintDC dc(this);for (UINT i = 0; i & m_vecChilds.size();i++)
{if (m_vecChilds[i]-&IsSelect())
CPen aNewPen,*pOldPint nOldRop = dc.SetROP2(R2_NOTXORPEN);
m_vecChilds[i]-&GetClientRect(rt);
rt.InflateRect(2,2);
m_vecChilds[i]-&ClientToScreen(rt);this-&ScreenToClient(rt);
aNewPen.CreatePen(PS_SOLID,3,m_colorFrame);
pOldPen = (CPen*)dc.SelectObject(aNewPen);
dc.Rectangle(rt);
dc.SelectObject(pOldPen);// 这里报错
dc.SetROP2(nOldRop);
  这段代码很诡异,有时候运行个两三个小时不会出错,有时候三五分钟就出错。请先不要着急看下面的错误分析,你能看出这段代码有什么问题吗?
  当初这段代码报错,说实话我一时半会还真没找到原因。最后看MSDN的关于CDC::SelectObject的相关文档,才终于找到原因。
  CDC::SelectObject重载了很多种方法。上面代码出错的原因是第一次调用使用的的函数原型是 HGDIOBJ CDC::SelectObject(HGDIOBJ),
而第二次使用的函数原型确是 CBitmap* CDC::SelectObject(CBitmap*)。对于上述代码第一次调用的时候,将HGDIOBJ强行转成CBitmap*实在有点惨不忍睹啊。。。。。。如此,便导致了悲催的崩溃。
浏览: 57232 次
来自: 昆明
三国杀。。。。。。。。。。。。。。。。。。。。。。。。。。。。 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'中国Java开发网 - [请教]用覆盖JFrame的paint方法画图的问题
Topic: [请教]用覆盖JFrame的paint方法画图的问题
1.[请教]用覆盖JFrame的paint方法画图的问题
Posted by: macroxmu
Posted on:
用覆盖paint(Graphics g)的方法画图,把窗口最大化和最小化时是正常的,但是在改变窗口大小后绘制的图形就消失了,请问是什么原因?是不是改变窗口大小这个事件无法repaint?应该如何解决?测试代码如下:/*
*/import javax.swing.*;import java.awt.*;public class pai extends JFrame{
public pai(){
this.setSize(800,500);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String args[]){
pai p=new pai();
public void paint(Graphics g){
g.drawLine(0,0,800,500);
2.Re:[请教]用覆盖JFrame的paint方法画图的问题
[Re: macroxmu]
Posted by: Infinite
Posted on:
“但是在改变窗口大小后绘制的图形就消失了,“???不明白什么意思,好像没有消失就是了。
3.Re:[请教]用覆盖JFrame的paint方法画图的问题
[Re: Infinite]
Posted by: macroxmu
Posted on:
现在是可以啊,但是只要你双击标题栏把这个窗口最大化的话里面画的线就消失了。
4.Re:[请教]用覆盖JFrame的paint方法画图的问题
[Re: macroxmu]
Posted by: Infinite
Posted on:
呵呵,我照做了,还是没问题,看看你提供的代码和你运行的版本有没有出入?macroxmu wrote:现在是可以啊,但是只要你双击标题栏把这个窗口最大化的话里面画的线就消失了。
5.Re:[请教]用覆盖JFrame的paint方法画图的问题
[Re: macroxmu]
Posted by: macroxmu
Posted on:
不可能吧-_||我用的是jdk1.5的附件中左边是把窗口拉大之前的,右边是把窗口拉大之后的。把窗口拉大之后里面画的线就消失了。当时把它最小化后在还原又出现了。
6.Re:[请教]用覆盖JFrame的paint方法画图的问题
[Re: macroxmu]
Posted by: losfound
Posted on:
窗口大小改变时重画窗口:import javax.swing.*;import java.awt.*;import java.awt.event.ComponentAimport java.awt.event.ComponentEpublic class pai extends JFrame {
public pai() {
this.setSize(800, 500);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String args[]) {
pai p = new pai();
p.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
e.getComponent().repaint();
public void paint(Graphics g) {
g.drawLine(0, 0, 800, 500);
7.Re:[请教]用覆盖JFrame的paint方法画图的问题
[Re: macroxmu]
Posted by: fairy_ap
Posted on:
俺也一样试过了,那个确实可以正常显示啊,即使与最大化来回切换也是显示正常的啊:)
Powered by & Version Jute 1.5.6 Ent
Copyright &
Cjsdn Team. All Righits Reserved.
客服电话&&&&&客服信箱&&&&&客服QQ&714923R画图中常见15个问题
1. How To Draw An Empty R Plot?
How To Open A New Plot Frame
You can open an empty plot frame and activate the graphics device in R as follows:
plot.new() # or frame()
Note&that the&plot.new()&and&frame()&functions
define a new plot frame without it having any axes, labels, or outlining. It indicates that a new plot is to be made: a new graphics window will open if you don't have one open yet, otherwise the existing window is prepared to hold the new plot. You can read
up on these functions&.
also opens a new windows device in R for the X Window System (version 11)!&starts
a graphics device driver for the OS X System.&starts
a new graphics device for Windows.&
How To Set Up The Measurements Of The Graphics Window
You can also use the&&function
to set the horizontal and vertical dimensions of the empty plot you just made:
pWidth = 3
pHeight = 2
plot.window(c(0,pWidth),
c(0,pHeight))
How To Draw An Actual Empty Plot
You can draw an empty plot with the&&function:
axes=FALSE,
ann=FALSE,
xlim=c(0, 10),
ylim = c(0,10))
You give the coordinates (5,5) for the plot, but that you don't show any plotting by putting the&type&argument
to&&n&. (Tip: try to put this argument to&&p&&or&&b&&and
see what happens!) What's more, you don't annotate the plot, but you do put limits from&0&to&10&on
the x- and y-axis.&Next, you can fill up your empty plot with axes, axes labels and a title with the following commands:
mtext(&x-axis&,
side=1) #Add text to the x-axis
mtext(&y-axis&,
title(&An R Plot&) #Add a title
Note&that if you want to know more about the&side&argument, you can just keep
on reading! It will be discussed in more detail below, in question 3 about R plots. Lastly, you may choose to draw a box around your plot by using the&&function
and add some points to it with the&&function:
box() #Draw a box
#Put (red) point in the plot at (5,5)
col=&red&)
col=&orange&,
points(c(0, 0, 1),
c(2, 4, 6),
col=&green&,
Note&that you can put your x-coordinates and y-coordinates in vectors to plot multiple points at once. The&pch&argument
allows you to select a symbol, while the&cex&argument has a value assigned to it that indicates how
much the plotted text and symbols should be scaled with respect to the default.Tip: if you want to see what number links to what symbol, click&.
2. How To Set The Axis Labels And Title Of The R Plots?
The axes of the R plots make up one of the most popular topics of Stack O The questions related to this topic are very diverse.&Keep on reading to find out what type of questions DataCamp has found to be quite common!
How To Name Axes (With Up- Or Subscripts) And Put A Title To An R Plot?
You can easily name the axes and put a title in place to make your R plot more specific and understandable for your audience. This can be easily done by adding the arguments&main&for
the main title,&sub&for the subtitle,&xlab&for
the label of the x-axis and&ylab&for the label of the y-axis:
x &- seq(0,2*pi,0.1)
y &- sin(x)
main=&main title&,
sub=&sub-title&,
xlab=&x-axis label&,
ylab=&y-axis label&)
Note&that if you want to have a title with up-or subscripts, you can easily add these with the following commands:
main=expression(&title&^2)) #Upscript
main=expression(&title&[2])) #Subscript
This all combined gives you the following plot:Good
to know:&for those who want to have Greek letters in your axis labels, the following code can be executed:
x &- seq(0,2*pi,0.1)
y &- sin(x)
xlab = expression(paste(&Greek letter &, phi)),
ylab = expression(paste(&Greek letter &,mu)))
How To Adjust The Appearance Of The Axes' Labels
To adjust the appearance of the x-and y-axis labels, you can use the arguments&col.lab&and&cex.lab.
The first argument is used to change the color of the x-and y-axis labels, while the second argument is used to determine the size of the x-and y-axis labels, relative to the (default) setting of&cex.
x &- seq(0,2*pi,0.1)
y &- sin(x)
main=expression(&main title&^2),
sub=expression(&sub-title&[2]),
xlab=&x-axis label&,
ylab=&y-axis label&,
col.lab=&blue&,
cex.lab=0.75)
more information on these arguments, go to&.
How To Remove A Plot's Axis Labels And Annotations
If you want to get rid of the axis values of a plot, you can first add the arguments&xaxt&and&yaxt,
set as&&n&. These arguments are assigned a character which specifies the x-axis type. If you put in
an&&n&, like in the command below, you can suppress the plotting of the axis.Note&that
by giving any other character to the&xaxt&and&yaxt&arguments,
the x-and y-axes are plotted. Next, you can add the annotation argument&ann&and set it to&FALSE&to
make sure that any axis labels are removed.
x &- seq(0,2*pi,0.1)
y &- sin(x)
ann=FALSE)
the information you are looking for? Go to&.
How To Rotate A Plot's Axis Labels
You can add the&las&argument to the&&function
to rotate the numbers that correspond to each axis:
x &- seq(0,2*pi,0.1)
y &- sin(x)
axes=FALSE)
this actually requires you to add an argument to the&&function
that basically says that there are no axes to be plotted (yet): this is the task of the two&axis()&function
that come next. The&las&argument can have three values attributed to it. According to whichever option
you choose, the placement of the label will differ: if you choose&0, the label will always be parallel
to the axis (which is the default); If you choose&1, the label will be put horizontally. Pick&2&if
you want it to be perpendicular to the axis and&3&if you want it to be placed vertically. But there
is more. If you want to know more about the possibilities of the&function,
keep on reading!
How To Move The Axis Labels Of Your R Plot
So, you want to move your axes' labels around? No worries, you can do this with the&&
As you may have noticed before in this tutorial, this function allows you to first specify where you want to draw the axes. Let's say you want to draw the x-axis above the plot area and the y-axis to the right of it.Remember&that if you
pass&1&or&2&to
the&&function,
your axis will be drawn on the bottom and on the left of the plot area. Scroll a bit up to see an example of this in the previous piece of code! This means that you will want to pass&3&and&4&to
the&&function:
x&-seq(0,2*pi,0.1)
axes=FALSE, # Do not plot any axes
ann=FALSE) # Do not plot any annotations
# Draw the x-axis above the plot area
# Draw the y-axis to the right of the plot area
you can see, at first, you basically plot&x&and&y,
but you leave out the axes and annotations. Then, you add the axes that you want to see and specify their location with respect to the plot. The flexibility that the&&function
creates for you keeps on growing! Check out the next frequently asked question to see what else you can solve by using this basic R function.Tip:&go to the last question to see more on how to move around text in the axis labels with&hjust&and&vjust!
3. How To Add And Change The Spacing Of The Tick Marks Of Your R Plot
How To Change The Spacing Of The Tick Marks Of Your R Plot
Letting R determine the tick marks of your plot can be quite annoying and there might come a time when you will want to adjust these.1. Using The&axis()&Function
To Determine The Tick Marks Of Your Plot&Consider the following piece of code:
v1 &- c(0,pi/2,pi,3*pi/2,2*pi) # -& defines position of tick marks.
v2 &- c(&0&,&Pi/2&,&Pi&,&3*Pi/2&,&2*Pi&) # defines labels of tick marks.
x &- seq(0,2*pi,0.1)
y &- sin(x)
xaxt = &n&)
axis(side = 1,
labels = v2,
you can see, you first define the position of the tick marks and their labels. Then, you draw your plot, specifying the x axis type as&&n&,
suppressing the plotting of the axis. Then, the real work starts:
The&&function
allows you to specify the side of the plot on which the axis is to be drawn. In this case, the argument is completed with&1,
which means that the axis is to be drawn below. If the value was&2, the axis would be drawn on the
left and if the value was&3&or&4,
the axis would be drawn above or to the right,The&at&argument allows you to indicate the points at which tick marks are to be drawn.
In this case, you use the positions that were defined in&V1;Likewise, the&labels&that you want to use are the ones that were specified in&V2;You adjust the direction of the ticks through&tck: by giving this argument a negative value,
you specify that the ticks should appear below the axis.&
Tip:&try passing a positive value to the&tck&argument and see what happens! You
can further specify the size of the ticks through&tcl&and the appearance of the tick labels is controlled
with&cex.axis,&col.axis&and&font.axis.
v1 &- c(0,pi/2,pi,3*pi/2,2*pi) # -& defines position of tick marks.
v2 &- c(&0&,&Pi/2&,&Pi&,&3*Pi/2&,&2*Pi&) # defines labels of tick marks.
x &- seq(0,2*pi,0.1)
y &- sin(x)
xaxt = &n&)
axis(side = 1,
labels = v2,
tcl = -0.5,
cex.axis=1.05,
col.axis=&blue&,
font.axis=5)
Using Other Functions To Determine The Tick Marks Of Your R Plot&You can also use the&&and&&functions
to define the positions of tickmarks and the number of intervals between them.Note&that then you use the argument&xaxp&to
which you pass the position of the tick marks that are located at the extremes of the x-axis, followed by the number of intervals between the tick marks:
x &- seq(0,2*pi,0.1)
y &- sin(x)
xaxp = c(0, 2*pi, 5))
x &- seq(0,2*pi,0.1)
y &- sin(x)
par(xaxp= c(0, 2*pi, 2))
this works only if you use no logarithmic scale. If the log coordinates set as true, or, in other words, if&par(xlog=T),
the three values that you pass to&xaxp&have a different meaning: for a small range, n is negative.
Otherwise, n is in 1:3, specifying a case number, and x1 and x2 are the lowest and highest power of 10 inside the user coordinates, 10 ^ par(“usr”)[1:2]. An example:
x &- seq(0, 10000, 1)
y &- exp(n)/(exp(n)+x)
par(xlog=TRUE,
xaxp= c(1, 4, 3))
this example, you use the&&function:
you set&xlog&to&TRUE&and
add the&xaxp&argument to give the coordinates of the extreme tick marks and the number of intervals
between them. In this case, you set the minimal value to&1, the maximal value to4&and
you add that the number of intervals between each tick mark should be&3. Then, you plot&x&and&y,
adding the&logargument to specify whether to plot the x-or y-axis or both on a log scale. You can pass&&x&,&&y&,
and&&xy&&as values to the log arguments to do this. An example with both axes in logarithmic scale
x &- seq(0, 20, 1)
y &- exp(x)/(x)
par(xlog=TRUE,
xaxp= c(1, 4, 3))
par(ylog=TRUE,
yaxp= c(1, 11, 2))
How To Add Minor Tick Marks To An R Plot
You can quickly add minor tick marks to your plot with the&&function
from the&&package:
plot.new()
library(Hmisc)
minor.tick(nx = 1.5,
tick.ratio=0.75)
The&nx&argument allows you to specify the number of intervals in which you want to divide
the area between the major tick marks on the axis. If you pass the value&1&to it, the minor tick marks
ny&allows you to do the same as&nx,
but then for the y-The&tick.ratio&indicates the ratio of lengths of minor tick marks to major tick marks.
The length of the latter is retrieved from&par(tck=x).&
4. How To Create Two Different X- or Y-axes
The first option is to create a first plot and to execute the&&function
with the&new&argument put to&TRUE&to
prevent R from clearing the graphics device:
set.seed(101)
y &- rnorm(10)
z &- runif(10, min=1000, max=10000)
plot(x, y)
par(new = TRUE)
Then, you create the second plot with&.
You make one of the type
type = &l&, #Plot with lines
axes = FALSE, #No axes
bty = &n&, #Box about plot is suppressed
xlab = &&,
#No labels on x-and y-axis
ylab = &&)
Note&that the with&axes&argument has been put to&FALSE,
while you also lave the x- and y-labels blank. You also add a new axis on the right-hand side by adding the argument&side&and
assigning it the value&4. Next, you specify the the&at&argument
to indicate the points at which tick-marks need to be drawn. In this case, you compute a sequence of n+1 equally spaced “round” values which cover the range of the values in&z&with
the&pretty()&function. This ensures that you actually have the numbers from the y-axis from your second
plot, which you named&z. Lastly, you add an axis label on the right-hand side:
axis(side=4,
at = pretty(range(z)))
mtext(&z&,
Note&that the&side&argument can have three values assigned to it:&1&to
place the text to the bottom,&2&for a left placement,&3&for
a top placement and&4&to put the text to the right. The&line&argument
indicates on which margin line the text starts. The end result will be like this:Tip:&Try
constructing an R plot with two different x-axes! You can find the solution below:
plot.new()
set.seed(101)
y &- rnorm(10)
z &- runif(10, min=1000, max=10000)
par(mar = c(5, 4, 4, 4) + 0.3)
plot(x, y)
par(new = TRUE)
plot(z, y, type = &l&, axes = FALSE, bty = &n&, xlab = &&, ylab = &&)
axis(side=3, at = pretty(range(z)))
mtext(&z&, side=3, line=3)
Note&that&&of
the plotrix package and&&of
the latticeExtra package automate this process:
library(latticeExtra)
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
Age &- chol$AGE
Chol &- chol$CHOL
Smoke &- chol$SMOKE
State &- chol$MORT
a &- xyplot(Chol ~ Age|State)
b &- xyplot(Smoke ~ Age|State)
doubleYScale(a, b, style1 = 0, style2 = 3, add.ylab2 = TRUE, columns=3)
the example above is made with&. If you're
not sure how you can import your data, check out our tutorial on.
5. How To Add Or Change The R Plot's Legend?
Adding And Changing An R Plot's Legend With Basic R
You can easily add a legend to your R plot with the&&function:
x &- seq(0,pi,0.1)
y1 &- cos(x)
y2 &- sin(x)
plot(c(0,3), c(0,3), type=&n&, xlab=&x&, ylab=&y&)
lines(x, y1, col=&red&, lwd=2)
lines(x, y2, col=&blue&, lwd=2)
legend(&topright&,
inset=.05,
title=&Legend&,
c(&Cosinus&,&Sinus&),
horiz=TRUE,
lty=c(1,1),
lwd=c(2,2),
col=c(&red&,&blue&),
bg=&grey96&)
the arguments&pt.cex&and&title.cex&that
are described in the documentation of&legend()&don't really work. There are some workarounds: 1.Put
the title or the labels of the legend in a different font with&text.font
x &- seq(0,pi,0.1)
y1 &- cos(x)
y2 &- sin(x)
plot(c(0,3), c(0,3), type=&n&, xlab=&x&, ylab=&y&)
lines(x, y1, col=&red&, lwd=2)
lines(x, y2, col=&blue&, lwd=2)
legend(&topright&,
inset=.05,
title=&Legend&,
c(&Cosinus&,&Sinus&),
horiz=TRUE,
lty=c(1,1),
lwd=c(2,2),
col=c(&red&,&blue&),
bg=&grey96&,
text.font=3)
Draw the legend twice with different&cex&values
x &- seq(0,pi,0.1)
y1 &- cos(x)
y2 &- sin(x)
plot(c(0,3), c(0,3), type=&n&, xlab=&x&, ylab=&y&)
lines(x, y1, col=&red&, lwd=2)
lines(x, y2, col=&blue&, lwd=2)
legend(&topright&,
inset=.05,
c(&Cosinus&,&Sinus&),
horiz=TRUE,
lty=c(1,1),
lwd=c(2,2),
col=c(&red&,&blue&))
legend(2.05, 2.97,
inset=.05,
title=&Legend&,
you're interested in knowing more about the colors that you can use in R, check out&&very
helpful PDF document.
How To Add And Change An R Plot's Legend And Labels In&ggplot2
Adding a legend to your ggplot2 plot is fairly easy. You can just execute the following:
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
library(ggplot2)
ggplot(chol, aes(x=chol$WEIGHT, y=chol$HEIGHT)) +
geom_point(aes(colour = factor(chol$MORT), shape=chol$SMOKE)) +
xlab(&Weight&) +
ylab(&Height&)
it gives you a default legend. But, in most cases, you will want to adjust the appearance of the legend some more. There are two ways of changing the legend title and labels in&:
1. If you have specified arguments such as&colour&or&shape,
or other aesthetics, you need to change the names and labels through&scale_color_discrete&and&scale_shape_discrete,
respectively:
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
library(ggplot2)
ggplot(chol, aes(x=chol$WEIGHT, y=chol$HEIGHT)) +
geom_point(aes(colour = factor(chol$MORT),
shape = chol$SMOKE)) +
xlab(&Weight&) +
ylab(&Height&) +
theme(legend.position=c(1,0.5),
legend.justification=c(1,1)) +
scale_color_discrete(name =&Condition&,
labels=c(&Alive&, &Dead&)) +
scale_shape_discrete(name=&Smoker&,
labels=c(&Non-smoker&, &Sigare&, &Pipe& ))
you can create two legends if you add the argument&shape&into the&&function
and into the&labelsarguments! If you want to move the legend to the bottom of the plot, you can specify
the&legend.position&as&&bottom&.
The&legend.justification&argument, on the other hand, allows you to position the legend inside the
plot.Tip:&check out all kinds of scales that could be used to let ggplot know that other names and labels should be used&.
2. Change the data frame so that the factor has the desired form.&For example:
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
levels(chol$SMOKE)[levels(chol$SMOKE)==&Non-smoker&] &- &Non-smoker&
levels(chol$SMOKE)[levels(chol$SMOKE)==&Sigare&] &- &Sigare&
levels(chol$SMOKE)[levels(chol$SMOKE)==&Pipe&] &- &Pipe&
names(chol)[names(chol)==&SMOKE&]
&- &Smoker&
You can then use the new factor names to make your plot in&, avoiding
the “hassle” of changing the names and labels with extra lines of code in your plotting.Tip:&for a complete cheat sheet on ggplot2, you can go&.
6. How To Draw A Grid In Your R Plot?
Drawing A Grid In Your R Plot With Basic R
For some purposes, you might find it necessary to include a grid in your plot. You can easily add a grid to your plot by using the&&function:
x &- c(1,2,3,4,5)
grid(10,10)
Drawing A Grid In An R Plot With&ggplot2
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
library(ggplot2)
ggplot(chol, aes(x=chol$WEIGHT, y=chol$HEIGHT)) +
geom_point(aes(colour = factor(chol$MORT), shape = chol$SMOKE)) +
xlab(&Weight&) +
ylab(&Height&) +
scale_color_discrete(name =&Condition&, labels=c(&Alive&, &Dead&)) +
scale_shape_discrete(name=&Smoker&, labels=c(&Non-smoker&, &Sigare&, &Pipe& )) +
theme(legend.position=c(1,0.5),
legend.justification=c(1,1),
panel.grid.major = element_line(colour = &grey40&),
panel.grid.minor = element_line(colour = &grey40&))
you don't want to have the minor grid lines, just pass&&to&panel.grid.minor.
If you want to fill the background up with a color, add the&panel.background = element_rect(fill = &navy&)&to
your code, just like this:
library(ggplot2)
ggplot(chol, aes(x=chol$WEIGHT, y=chol$HEIGHT)) +
geom_point(aes(colour = factor(chol$MORT), shape = chol$SMOKE)) +
xlab(&Weight&) +
ylab(&Height&) +
scale_color_discrete(name =&Condition&, labels=c(&Alive&, &Dead&)) +
scale_shape_discrete(name=&Smoker&, labels=c(&Non-smoker&, &Sigare&, &Pipe& )) +
theme(legend.position=c(1,0.5),
legend.justification=c(1,1),
panel.grid.major = element_line(colour = &grey40&),
panel.grid.minor = element_line(colour = &grey40&),
panel.background = element_rect(fill = &navy&)
7. How To Draw A Plot With A PNG As Background?
You can quickly draw a plot with a .png as a background with the help of the&&package.
You install the package if you need to, activate it for use in your workspace through the library function&library()&and
you can start plotting!
install.packages(&png&)
library(png)
First, you want to load in the image. Use the&&function
to specify the path to the picture!
image &- readPNG(&&path to your picture&&)
Tip:&you can check where your working directory is set at and change it by executing the following commands:
setwd(&&path to a folder&&)
If your picture is saved in your working directory, you can just specify&readPNG(&picture.png&)&instead
of passing the whole path. Next, you want to set up the plot area:
plot(1:2, type='n', main=&Plotting Over an Image&, xlab=&x&, ylab=&y&)
And you want to call the&par()&function:
lim &- par()
You can use the&par()&function to set the graphical parameters in&.
You use the argument&usr&to define the extremes of the user coordinates of the plotting region. In
this case, you put&1,&3,&2&and&4:
rasterImage(image, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
Next, you draw a grid and add some lines:
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1, 1.3, 1.7, 1.6, 1.7, 1.0), type=&b&, lwd=5, col=&red&)
This can give you the following result if you use the DataCamp logo:
library(png)
image &- readPNG(&datacamp.png&)
plot(1:2, type=&n&, main=&Plotting Over an Image&, xlab=&x&, ylab=&y&, asp=1)
lim &- par()
rasterImage(image, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1.5, 1.3, 1.7, 1.6, 1.7, 1.0), type=&b&, lwd=5, col=&red&)
you need to give a .png file as input to&readPNG()!
8. How To Adjust The Size Of Points In An R Plot?
Adjusting The Size Of Points In An R Plot With Basic R
To adjust the size of the points with basic R, you might just simply use the&cex&argument:
x &- c(1,2,3,4,5)
y &- c(6,7,8,9,10)
plot(x,y,cex=2,col=&red&)
Remember, however, that that R allows you to have much more control over your symbols through the function&:
df &- data.frame(x1=1:10,
x2=sample(10:99, 10),
symbols(x=df$x1,
circles=df$x3,
inches=1/3,
bg=&steelblue2&,
The circles of this plot receive the values of&df$x3&as the radii, while the argument&inches&controls
the size of the symbols. When this argument receives a positive number as input, the symbols are scaled to make largest dimension this size in inches.
Adjusting The Size Of Points In Your R Plot With&ggplot2
In this case, you will want to adjust the size of the points in your scatterplot. You can do this with the&size&argument:
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
ggplot(chol,
aes(x=chol$WEIGHT, y=chol$HEIGHT),
size = 2) +
geom_point()
ggplot(chol,
aes(x=chol$WEIGHT, y=chol$HEIGHT)) +
geom_point(size = 2)
9. How To Fit A Smooth Curve To Your R Data
The&&function
is probably every R programmer's favorite solution for this kind of question. It actually “fits a polynomial surface determined by one or more numerical predictors, using local fitting”. In short, you have your data:
y &- c(2,4,6,8,7,12,14,16,18,20)
And you use the&&function,
in which you correlate y and x. Through this, you specify the numeric response and one to four numeric predictors:
lo &- loess(y~x) ### estimations between data
You plot x and y:
And you plot lines in the original plot where you predict the values of&lo:
lines(predict(lo))
Which gives you the following plot:
10. How To Add Error Bars In An R Plot
Drawing Error Bars With Basic R
The bad news: R can't draw error bars just like that. The good news: you can still draw the error bars without needing to install extra packages!
#Load the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Calculate some statistics for the chol dataset
library(Rmisc)
cholc &- summarySE(chol,
measurevar=&CHOL&,
groupvars=c(&MORT&,&SMOKE&))
#Plot the data
plot(cholc$N,
cholc$CHOL,
ylim=range(c(cholc$CHOL-cholc$sd, cholc$CHOL+cholc$sd)),
xlab=&Cholesterol Measurements&,
ylab=&Cholesterol Mean +/- SD&,
main=&Scatterplot With sd Error Bars&
#Draw arrows of a &special& type
arrows(cholc$N,
cholc$CHOL-cholc$sd,
cholc$CHOL+cholc$sd,
length=0.05,
If you want to read up on all the arguments that&arrows()&can take, go&.
Drawing Error Bars With&ggplot2
Error Bars Representing Standard Error Of Mean
First summarize your data with the&&function
from the&&package:
#Load in the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Calculate some statistics for the chol dataset
library(Rmisc)
cholc &- summarySE(chol,
measurevar=&CHOL&,
groupvars=c(&MORT&,&SMOKE&))
Then, you can use the resulting dataframe to plot some of the variables, drawing error bars for them at the same time, with, for example, the standard error of mean:If
you want to change the position of the error bars, for example, when they overlap, you might consider using the&&function:
#Load in the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Calculate some statistics for the chol dataset
library(Rmisc)
cholc &- summarySE(chol,
measurevar=&CHOL&,
groupvars=c(&MORT&,&SMOKE&))
#Plot the cholc dataset
library(ggplot2)
pd &- position_dodge(0.1)
ggplot(cholc, aes(x=SMOKE, y=CHOL, colour=MORT)) +
geom_errorbar(aes(ymin=CHOL-se, ymax=CHOL+se, group=MORT),
position=pd) +
geom_line(aes(group=MORT)) +
geom_point()
you get an error like “geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?”, it usually requires you to adjust the group aesthetic.
Error Bars Representing Confidence Intervals
Continuing from the summary of your data that you made with the&&function,
you can also draw error bars that represent confidence intervals. In this case, a plot with error bars of 95% confidence are plotted.
#Load in the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Calculate some statistics for the chol dataset
library(Rmisc)
cholc &- summarySE(chol,
measurevar=&CHOL&,
groupvars=c(&MORT&,&SMOKE&))
#Plot the cholc dataset
library(ggplot2)
pd &- position_dodge(0.1)
ggplot(cholc, aes(x=SMOKE, y=CHOL, colour=MORT)) +
geom_errorbar(aes(ymin=CHOL-ci, ymax=CHOL+ci, group=MORT),
colour=&black&,
position=pd) +
geom_line(aes(group=MORT)) +
geom_point()
the color of the error bars is now set to black with the&colour&argument.
Error Bars Representing The Standard Deviation
Lastly, you can also use the results of the&&function
to plot error bars that represent the standard deviation. Specifically, you would just have to adjust the&ymin&and&ymax&arguments
that you pass to&geom_errorbar():
#Load in the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Calculate some statistics for the chol dataset
library(Rmisc)
cholc &- summarySE(chol,
measurevar=&CHOL&,
groupvars=c(&MORT&,&SMOKE&))
#Plot the cholc dataset
library(ggplot2)
pd &- position_dodge(0.1)
ggplot(cholc, aes(x=SMOKE, y=CHOL, colour=MORT)) +
geom_errorbar(aes(ymin=CHOL-sd, ymax=CHOL+sd, group=MORT),
position=pd) +
geom_line(aes(group=MORT)) +
geom_point()
Big tip:&also take a look at&&for
more detailed examples on how to plot means and error bars.
11. How To Save A Plot As An Image On Disc
You can use&&to copy your graph, made in the
current graphics device to the device or folder specified by yourself.
x &- seq(0,2*pi,0.1)
y &- sin(x)
dev.copy(jpeg,
filename=&&path to your file/name.jpg&&);
dev.off();
12. How To Plot Two R Plots Next To Each Other?
How To Plot Two Plots Side By Side Using Basic R
You can do this with basic R commands:
d0 &- matrix(rnorm(15), ncol=3)
d1 &- matrix(rnorm(15), ncol=3)
limits &- range(d0,d1) #Set limits
par(mfrow = c(1, 2))
boxplot(d0,
ylim=limits)
boxplot(d1,
ylim=limits)
By adding the&&function
with the&mfrow&argument, you specify a vector, which in this case contains 1 and 2: all figures will
then be drawn in a 1-by-2 array on the device by rows (mfrow). In other words, the boxplots from above
will be printed in one row inside two columns.
How To Plot Two Plots Next To Each Other Using&ggplot2
If you want to put plots side by side and if you don't want to specify limits, you can consider using the&&package
to draw your plots side-by-side:
#Load in the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Calculate some statistics for the chol dataset
library(Rmisc)
cholc &- summarySE(chol,
measurevar=&CHOL&,
groupvars=c(&MORT&,&SMOKE&))
#Plot the cholc dataset
library(ggplot2)
ggplot(cholc, aes(x=SMOKE, y=CHOL, colour=MORT)) +
geom_errorbar(aes(ymin=CHOL-sd, ymax=CHOL+sd, group=MORT),
position=pd) +
geom_line(aes(group=MORT)) +
geom_point() +
facet_grid(. ~ MORT)
you just add the&&function
to indicate that you want two plots next to each other. The element that is used to determine how the plots are drawn, is&MORT,
as you can well see above!
How To Plot More Plots Side By Side Using&gridExtra
To get plots printed side by side, you can use the&&
Make sure you have the package installed and activated in your workspace and then execute something like this:
library(gridExtra)
plot1 &- qplot(1)
plot2 &- qplot(1)
grid.arrange(plot1,
Note&how here again you determine how the two plots will appear to you thanks to the&ncol&argument.
How To Plot More Plots Side By Side Using&lattice
Just like the solution with&&package,
the&&package
also doesn't require you to specify limits or the way you want your plots printed next to each other. Instead, you use&&to
make trellis graphs with the graph type of a box plot.&Trellis graphs&display a variable or the relationship between variables, conditioned on one or more other variables. In this case, if you're using the&chol&data
set (which you can find&&or load in with the&read.table()&function
given below), you display the variable&CHOL&separately for every combination of factor&SMOKE&and&MORT&levels:
#Load in the data
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
#Plot two plots side by side
library(lattice)
bwplot(~ CHOL|SMOKE+MORT,
Plotting Plots Next To Each Other With&gridBase
Another way even to put two plots next to each other is by using the&&package,
which takes care of the “integration of base and grid graphics”. This could be handy when you want to put a basic R plot and a ggplot next to each other. You work as follows: first, you activate the necessary packages in your workspace. In this case, you want
to have&&ready
to put the two plots next to each other and&&and&&to
actually make your plots:
library(grid)
library(gridBase)
library(ggplot2)
plot.new()
gl &- grid.layout(nrow=1,
vp.1 &- viewport(layout.pos.col=1,
layout.pos.row=1)
vp.2 &- viewport(layout.pos.col=2,
layout.pos.row=1)
pushViewport(viewport(layout=gl))
pushViewport(vp.1)
par(new=TRUE,
fig=gridFIG())
plot(x = 1:10,
popViewport()
pushViewport(vp.2)
ggplotted &- qplot(x=1:10,y=10:1, 'point')
print(ggplotted, newpage = FALSE)
popViewport(1)
you want and need it, you can start an empty plot:
plot.new()
To then set up the layout:
gl &- grid.layout(nrow=1,
Note&that since you want the two plots to be generated next to each other, this requires you to make a grid layout consisting of one row and two columns. Now, you want to fill up the cells of the grid with viewports. These define rectangular
regions on your graphics device with the help of coordinates within those regions. In this case, it's much more handy to use the specifications of the grid that have just been described above rather than real x-or y-coordinates. That is why you should use
the&layout.pos.col&and&layout.pos.row&arguments:
vp.1 &- viewport(layout.pos.col=1,
layout.pos.row=1)
vp.2 &- viewport(layout.pos.col=2,
layout.pos.row=1)
Note&again that since you want the two plots to be generated next to each other, you want to put one plot in the first column and the other in the second column, both located on the first row. Since the viewports are only descriptions
or definitions, these kinds of objects need to be pushed onto the viewport tree before you can see any effect on the drawing. You want to use the&&function
to accomplish this:
pushViewport(viewport(layout=gl))
Note&the&&function
takes the&&function,
which in itself contains a&layout&argument. This last argument indicates “a grid layout object which
splits the viewport into subregions”.Remember&that you started out making one of those objects. Now you can proceed to adding the first rectangular region&vp.1&to
the ViewPort tree:
pushViewport(vp.1)
After which you tell R with&&to
draw a base plot within a grid viewport (vp.1, that is). The&fig&argument
normally takes the coordinates of the figure region in the display region of the device. In this case, you use the&fig&argument
to start a new plot, adding it to an existing plot use by adding&new = TRUE&in the&&function
as well. You plot the base graphic and remove the viewport from the tree:
par(new=TRUE,
fig=gridFIG())
plot(x = 1:10,
popViewport()
Note&that you can specify in the&&function
an argument to indicate how many viewports you want to remove from the tree. If this value is 0, this indicates that you want to remove the viewports right up to the root viewport. The default value of this argument is 1. Go to add the second rectangular region&vp.2&to
the ViewPort tree. You can then make the ggplot and remove the viewport from the tree.
pushViewport(vp.2)
ggplotted &- qplot(x=1:10,
print(ggplotted,
newpage = FALSE)
popViewport(1)
Note&that you need to print to print the graphics object made by&&in
order to actually draw it and get it displayed. At the same time, you also want to specify&newpage = FALSE,
otherwise you'll only see the&…
Also&remember&that the default value of viewports to remove in the function&&is
set at 1. This makes it kind of redundant to put&popViewport(1)in the code.
13. How To Plot Multiple Lines Or Points?
Using Basic R To Plot Multiple Lines Or Points In The Same R Plot
To plot two or more graphs in the same plot, you basically start by making a usual basic plot in R. An example of this could be:
x &- seq(0,pi,0.1)
y1 &- cos(x)
col = &red&)
Then, you start adding more lines or points to the plot. In this case, you add more lines to the plot, so you'll define more y axes:
y2 &- sin(x)
y3 &- tan(x)
y4 &- log(x)
Then, you plot these y axes with the use of the&&function:
lines(x,y2,col=&green&)
lines(x,y2,col=&green&)
lines(x,y3,col=&black&)
lines(x,y4,col=&blue&)
This gives the following result:Note&that
the&&function
takes in three arguments: the x-axis and the y-axis that you want to plot and the color (represented with the argument&col)
in which you want to plot them. You can also include the following features:
Integer or character string
Line width
Integer or single character
Line end style
Integer or string
Line join style
Integer or string
Line mitre limit
Integer & 1
Here are some examples:
lines(x,y2,col=&green&, lty = 2, lwd = 3)
lines(x,y2,col=&green&, lty = 5, lwd = 2, pch = 2)
lines(x,y3,col=&black&, lty = 3, lwd = 5, pch = 3, lend = 0, ljoin = 2)
lines(x,y4,col=&blue&, lty = 1, lwd = 2, pch = 3, lend = 2, ljoin = 1, lmitre = 2)
Note&that the&pch&argument does not function all that well with the&&function
and that it's best to use it only with&.Tip:&if
you want to plot points in the same graph, you can use the&&function:
col=&yellow&)
You can add the same arguments to the&&function
as you did with the&&function
and that are listed above. There are some additions, though:
Background (fill) color
Only if&pch = 21:25
Character (or symbol) expansion
Code examples of these arguments are the following:
points(x,y4,col=&blue&, pch=21, bg = &red&)
points(x, y5, col=&yellow&, pch = 5, bg = &blue&)
If you incorporate these changes into the plot that you see above, you will get the following result:
x &- seq(0,pi,0.1)
y1 &- cos(x)
plot(x,y1,type=&l& ,col = &red&) #basic graphical object
y2 &- sin(x)
y3 &- tan(x)
y4 &- log(x)
lines(x,y2,col=&green&, lty = 1, lwd = 3) #first layer
lines(x,y2,col=&green&, lty = 3, lwd = 2, pch = 2) #second layer
lines(x,y3,col=&black&, lty = 2, lwd = 1, pch = 3, lend = 0, ljoin = 2) #third layer
points(x,y4,col=&blue&, pch=21, bg = &red&) #fourth layer
points(x, y5, col=&yellow&, pch = 24, bg = &blue&) #fifth layer
Using&ggplot2&To Plot Multiple Lines Or Points In One R Plot
The&&package
conveniently allows you to also create layers, which allows you to basically plot two or more graphs into the same R plot without any difficulties and pretty easily:
library(ggplot2)
y1 &- c(2,4,6,8,7,12,14,16,18,20)
y2 &- rnorm(10, mean = 5)
df &- data.frame(x, y1, y2)
ggplot(df, aes(x)) +
# basic graphical object
geom_line(aes(y=y1),
colour=&red&) +
# first layer
geom_line(aes(y=y2),
# second layer
colour=&green&)
14. How To Fix The Aspect Ratio For Your R Plots
If you want to put your R plot to be saved as an image where the axes are proportional to their size, it's a sign that you want to fix the aspect ratio.
Adjusting The Aspect Ratio With Basic R
When you're working with basic R commands to produce your plots, you can add the argument&asp&of the&&function,
completed with an integer, to set your aspect ratio. Look at this first example without a defined aspect ratio:
x &- seq(0,2*pi,0.1)
y &- sin(x)
compare this now to the plot where the aspect ratio is defined with the argument&asp:
x &- seq(0,2*pi,0.1)
y &- sin(x)
Adjusting The Aspect Ratio For Your Plots With&ggplot2
To fix the aspect ratio for ggplot2 plots, you just add the function&,
which provides a “fixed scale coordinate system [that] forces a specified ratio between the physical representation of data units on the axes”. In other words, this function allows you to specify a number of units on the y-axis which is equivalent to one unit
on the x-axis. The default is always set at 1, which means that one unit on the x-axis has the same length as one unit on the y-axis. If your ratio is set at a higher value, the units on the y-axis are longer than units on the x-axis and vice versa. Compare
the following examples:
library(ggplot2)
df &- data.frame(
x = runif(100, 0, 5),
y = runif(100, 0, 5))
ggplot(df, aes(x=x, y=y)) + geom_point()
library(ggplot2)
df &- data.frame(
x = runif(100, 0, 5),
y = runif(100, 0, 5))
ggplot(df, aes(x=x, y=y)) +
geom_point() +
coord_fixed(ratio=1)
Adjusting The Aspect Ratio For Your Plots With&MASS
You can also consider using the&&package, which encompasses the&&function:
it produces plots with geometrically equal scales. It does this for scatterplots:
chol &- read.table(url(&http://assets.datacamp.com/blog_assets/chol.txt&), header = TRUE)
library(MASS)
x = chol$HEIGHT
y = chol$WEIGHT
z = as.numeric(chol$MORT)
eqscplot(x,
ratio = 1,
col=c(&red&, &green&),
pch=c(1,2))
might do well starting a new plot frame before executing the code above!Note&that you can give additional arguments to the&&function
to customize the scatterplot's look!
15. What Is The Function Of&hjust&And&vjust&In&ggplot2?
Well, you basically use these arguments when you want to set the position of text in your ggplot.&hjust&allows
you to define the horizontal justification, while&vjust&is meant to control the vertical justification.
See the documentation on&&for
more information. To demonstrate what exactly happens, you can create a data frame from all combinations of factors with the&&function:
hjustvjust &- expand.grid(hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text=&Text&
Note&that&hjust&and&vjust&can
only take values between&0&and&1.
0&means that the text is left- In other words, all text is aligned to the left
margin. This is usually what you see when working with text editors such as Word.1&means that the text is right-justified: all text is aligned to the right margin.&
Then, you can plot the data frame that you have just made above with the&&function,
defining the x-and y-axis as “hjust” and “vjust” respectively:
library(ggplot2)
ggplot(hjustvjust, aes(x=hjust, y=vjust)) +
geom_point() +
geom_text(aes(label=text,
angle=angle,
hjust=hjust,
vjust=vjust)) +
facet_grid(~angle) +
scale_x_continuous(breaks=c(0, 0.5, 1),
expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1),
expand=c(0, 0.2))
Also&note&how
the&hjust&and&vjust&arguments
are added to&geom_text(), which takes care of the textual annotations to the plot. In the plot above
you see that the text at the point (0,0) is left-aligned, horizontally as well as vertically. On the other hand, the text at point (1,1) is right-aligned in horizontal as well as vertical direction. The point (0.5,0.5) is right in the middle: it's not really
left-aligned nor right-aligned for what concerns the horizontal and vertical directions.Note&that when these arguments are defined to change the axis text, the horizontal alignment for axis text is defined in relation to the entire plot,
not to the x-axis!
DF &- data.frame(x=LETTERS[1:3],
p &- ggplot(DF, aes(x,y)) +
geom_point() +
ylab(&Very long label for y&) +
theme(axis.title.y=element_text(angle=0))
p1 &- p + theme(axis.title.x=element_text(hjust=0)) + xlab(&X-axis at hjust=0&)
p2 &- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab(&X-axis at hjust=0.5&)
p3 &- p + theme(axis.title.x=element_text(hjust=1)) + xlab(&X-axis at hjust=1&)
library(gridExtra)
grid.arrange(p1, p2, p3)
try for yourself what defining the&vjust&agument to change the axis text does to the representation
of your plot:
DF &- data.frame(x=c(&a\na&,&b&,&cdefghijk&,&l&),
p &- ggplot(DF, aes(x,y)) + geom_point()
p1 &- p + theme(axis.text.x=element_text(vjust=0, colour=&red&)) +
xlab(&X-axis labels aligned with vjust=0&)
p2 &- p + theme(axis.text.x=element_text(vjust=0.5, colour=&red&)) +
xlab(&X-axis labels aligned with vjust=0.5&)
p3 &- p + theme(axis.text.x=element_text(vjust=1, colour=&red&)) +
xlab(&X-axis labels aligned with vjust=1&)
library(gridExtra)
grid.arrange(p1,p2,p3)
To go to the original excellent discussion, from which the code above was adopted, click&.
没有更多推荐了,

我要回帖

更多关于 绘图园林花镜 的文章

 

随机推荐