R列数据框名称编号

时间:2018-08-06 14:26:19

标签: r ggplot2

我有一个这样的数据框

geo 2001    2002
Spain   21  23
Germany 34  50
Italy   57  89
France  19  13

由于第2列和第3列的名称被视为数字,因此我无法获得带有ggplot2的条形图。有什么解决方法可以将列名设置为文本?

数据

pivot_dat <- read.table(text="geo 2001    2002
Spain   21  23
Germany 34  50
Italy   57  89
France  19  13",strin=F,h=T)
pivot_dat <- setNames(pivot_dat,c("geo","2001","2002"))

2 个答案:

答案 0 :(得分:2)

方法如下:

import React from 'react';
import { StyleSheet, View } from 'react-native';

import { LoginManager, AccessToken, LoginButton } from 'react-native-fbsdk';

import firebase from 'react-native-firebase';

export default class App extends React.Component {
  fbLoginHandler(error, result) {
    if (error) {
      alert('Login failed with error: ' + error);
    } else if (result && result.isCancelled) {
      alert('Login cancelled');
    } else {
      AccessToken.getCurrentAccessToken().then((accessTokenData) => {
        const credential = firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
        firebase.auth().signInAndRetrieveDataWithCredential(credential).then((s) => {
          alert('Success! ' + s);
        }, (signinError) => {
          console.log('Signin error', signinError);
          alert('Signin error' + signinError);
        });
      }, (tokenError) => {
        alert('Some error occurred' + tokenError);
      });
    }
  }

  render () {
    return (
      <View style={styles.container}>
        <LoginButton
          readPermissions={['public_profile', 'email']}
          onLoginFinished={(error, result) => this.fbLoginHandler(error, result)}
          onLogoutFinished={() => alert('logout.')}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  }
});

通过使用刻度而不是双引号/双引号,可以确保将名称传递给函数而不是字符串。

如果使用引号,library(ggplot2) ggplot(pivot_dat, aes(x = geo, y = `2002`)) + geom_col()+ coord_flip() 会将此字符值转换为因子并回收利用,因此所有条形图的长度都将为ggplot,并且标签值为1

注释1

您可能想了解"2002"geom_col之间的区别:

geom_bar

简而言之,?ggplot2::geom_bar geom_colgeom_bar,这是您想要的,因为您希望在绘图上显示表中的原始值。

注释2

stat = "identity"可用于提供字符串而不是名称,但此处无效,因为aes_string被评估为数字:

"2002"

答案 1 :(得分:0)

没有示例可以确切地了解您的问题是什么,您想要什么,很难给您一个完美的答案。但这就是事情。

您可以使用数字数据执行geom_bar。我认为您可能会遇到3种可能的问题(但我可能无法一概而论。

首先,让我们设置r进行绘图。

library(readr)
library(ggplot2)

test <- read_csv("geo,2001,2002
Spain,21,23
Germany,34,50
Italy,57,89
France,19,13")

接下来,让我们犯第一个错误...错误地调用列名。在下一个示例中,我将告诉ggplot制作一个数字2001的小节。不是列2001! r必须猜测是2001年还是对象2001。默认情况下,它总是选择数字而不是列。

ggplot(test) +
  geom_bar(aes(x=2001))

enter image description here

好吧,这只为您提供2001年的小节...因为您给了它一个数字输入而不是一列。让我们修复它。使用右引号``标识列名2001而不是数字2001。

ggplot(test) +
  geom_bar(aes(x=`2001`))

enter image description here

这将创建一个完美可行的条形图。但是也许您不想要空格?这是您使用文本而不是数字的唯一可能原因。但是您需要文本,因此我将向您展示如何使用as.factor进行类似的操作(功能更强大)。

ggplot(test) +
  geom_bar(aes(x=as.factor(`2001`)))

enter image description here