将aes(x = ...)放在ggplot()或geom()中的区别

时间:2021-12-07 14:55:05

What is the difference between putting aes(x=…) in ggplot() or in geom() (e.g. geom_histogram() below):

将aes(x = ...)放在ggplot()或geom()中有什么区别(例如下面的geom_histogram()):

1. in ggplot():

1.在ggplot()中:

ggplot(diamonds) + 
  geom_histogram(binwidth=500, aes(x=diamonds$price))+ 
  xlab("Diamond Price U$") + ylab("Frequency")+ 
  ggtitle("Diamond Price Distribution")

将aes(x = ...)放在ggplot()或geom()中的区别

2. in the geom():

2.在geom()中:

ggplot(diamonds, aes(x=diamonds$price)) + 
  geom_histogram(bidwidth= 500) + 
  xlab("Price") + ylab("Frequncy") + 
  ggtitle("Diamonds Price distribution")

将aes(x = ...)放在ggplot()或geom()中的区别

1 个解决方案

#1


2  

Whether you put x = price in the original ggplot() call or in a specific geom only really matters if you have multiple geoms with different mappings. The mapping you specify in the ggplot() call will be applied to all geoms, so it's often best to put the mapping in the top level like that, if only to save you having to type it out again for each individual geom. Specify mappings in the individual geoms if they only apply to that specific geom.

无论你将x = price放在原始的ggplot()调用中还是在特定的geom中,只有你有多个具有不同映射的geom才真正重要。您在ggplot()调用中指定的映射将应用于所有geom,因此通常最好将映射放在顶层,如果只是为了节省您必须为每个单独的geom再次键入它。如果它们仅适用于特定的geom,请指定各个geom中的映射。

Also note that it should just be aes(x = price), not aes(x = diamonds$price). ggplot knows to look in the dataframe you're using as your data argument. If you pass a vector manually like diamonds$price you might mess up facetting or grouping in a more complex plot.

另请注意,它应该只是aes(x =价格),而不是aes(x =钻石$ price)。 ggplot知道要查看您用作数据参数的数据帧。如果你手动传递矢量像钻石一样价格,你可能会在更复杂的情节中弄乱分面或分组。

#1


2  

Whether you put x = price in the original ggplot() call or in a specific geom only really matters if you have multiple geoms with different mappings. The mapping you specify in the ggplot() call will be applied to all geoms, so it's often best to put the mapping in the top level like that, if only to save you having to type it out again for each individual geom. Specify mappings in the individual geoms if they only apply to that specific geom.

无论你将x = price放在原始的ggplot()调用中还是在特定的geom中,只有你有多个具有不同映射的geom才真正重要。您在ggplot()调用中指定的映射将应用于所有geom,因此通常最好将映射放在顶层,如果只是为了节省您必须为每个单独的geom再次键入它。如果它们仅适用于特定的geom,请指定各个geom中的映射。

Also note that it should just be aes(x = price), not aes(x = diamonds$price). ggplot knows to look in the dataframe you're using as your data argument. If you pass a vector manually like diamonds$price you might mess up facetting or grouping in a more complex plot.

另请注意,它应该只是aes(x =价格),而不是aes(x =钻石$ price)。 ggplot知道要查看您用作数据参数的数据帧。如果你手动传递矢量像钻石一样价格,你可能会在更复杂的情节中弄乱分面或分组。