如何使用seaborn pairgird和seaborn barplot为每个情节添加颜色和星号

时间:2017-01-03 00:11:08

标签: python matplotlib seaborn

我想绘制3个水平条形图,标签为y轴,数据为x轴,我希望每个绘图都是不同的颜色,并且有一些类型的注释,如星号取决于关于由数据中的列表示的符号,例如:

class Social extends Component {
                constructor(props) {
                    super(props);

                    var tabLabel = this.props.tabLabel;

                    var dataSource = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
                    this.state = {
                        text: 'Search ' + tabLabel + ' here...' ,
                        textInput: '',
                        dataSource:dataSource,
                    };
                  }

                    loadMoreContentAsync = async () => {
                        this.doneClick();
                      }


                  renderRow(rowData: object, sectionID: number, rowID: number) {
                      return (
                        <TouchableHighlight
                          underlayColor = '#ddd'>
                          <View style ={styles.row}>
                            <View style={styles.imagecon}>
                              <Image style={{width: 100, height: 80}} source={{uri: rowData.thumbnail}}  />
                            </View>
                            <View style={styles.textcon}>
                                <Text style={{ fontSize: 11, fontWeight: 'bold' }} > {rowData.title}  </Text>
                                <Text style={{ fontSize: 11}} > {rowData.desc}  </Text>
                            </View>
                          </View>
                        </TouchableHighlight>

                      )
                    }
                        doneClick = () => {
                            this.props.showTrans();
                            fetch("https://www.googleapis.com/youtube/v3/search?part=snippet&q=tupac&key=AIzaSyDFOz50C_XkuEh2T-2XTN9fqm_5xHYzbg8")
                              .then((response) => response.json())
                              .then((responseData) => {
                                console.log('fxbxfbxf' + responseData.toString());
                                console.log('ghghgh' + responseData["items"].length);
                                var arrVideos = new Array;
                                //let doc = new DomParser().parseFromString(html,'text/html')
                                for(var i = 0; i < responseData["items"].length; i++) {
                                    var title = responseData["items"][i]["snippet"].title;
                                    var thumbnail = responseData["items"][i]["snippet"]["thumbnails"]["default"]["url"];
                                    var desc = responseData["items"][i]["snippet"]["description"];

                                    var video = {
                                        title : title,
                                        thumbnail: thumbnail,
                                        desc: desc
                                    }

                                    arrVideos.push(video);
                                }

                                this.setState({
                                    dataSource: this.state.dataSource.cloneWithRows(arrVideos)
                                });
                                this.props.hideTrans();
                              })
                              .done();
                        }
                          render() {

                            return (
                                <View style={styles.menu} >


                                        <View style={styles.searchbar} >
                                        <Image style={{marginTop: 10 ,marginLeft: 10 , width: 20, height: 20}} source={require('./images/search.png')} />
                                        <TextInput
                                                onSubmitEditing={ this.doneClick }
                                             style={{marginLeft: 5, color: '#757575', width: width - 80, height: 40, fontSize: 11,}}
                                             onChangeText={(textInput) => this.setState({textInput})}
                                             placeholder={this.state.text}
                                              underlineColorAndroid="transparent"
                                             />
                                    </View>
                                    <View style={styles.sep} >
                                    </View>

                                      <ListView
                                      renderScrollComponent={props => <InfiniteScrollView {...props} />}
                                        style = {{flexDirection: 'column',
                                                      }}
                                        dataSource = {this.state.dataSource}
                                        renderRow = {this.renderRow.bind(this)}
                                        renderFooter={() => <Footer />}
                                        onLoadMoreAsync={this.loadMoreContentAsync}
                                        >
                                      </ListView>
                                </View>

                            );
                          }
                        }


const styles = StyleSheet.create({
                   menu: {
                   flex:1,flexDirection: 'column',
                           },
                           searchbar: {
                               alignItems: 'flex-start',
                                flexDirection: 'row',
                            },
                           sep: {
                               alignItems: 'flex-start',
                               height: 1,
                               width: width,
                               backgroundColor: '#9E9E9E',
                            },
                           row: {
                               padding: 10,
                                  flex: 1,
                                  width: width,
                                  height:120,
                                  borderBottomWidth: 1,
                                  borderBottomColor: '#9E9E9E',
                                  flexDirection: 'row',
                           },
                           imagecon: {
                           backgroundColor: 'black',
                                padding: 5,
                             alignItems: 'center',
                          },
                           textcon: {
                              paddingLeft: 8,
                              flex: 1,
                                alignItems: 'flex-start',
                             },
                           textstyle: {
                                  fontSize: 11,
                            },
                              container: {
                                flex: 1,
                                padding: 8,
                                alignItems: 'center',
                                justifyContent: 'center',
                              },
                              button: {
                                borderColor: '#8E8E8E',
                                borderWidth: StyleSheet.hairlineWidth,
                                paddingHorizontal: 20,
                                paddingVertical: 10,
                                borderRadius: 5,
                              },
                              text: {
                                color: '#8E8E8E',
                              },
                           });

会给我这样的东西:

enter image description here

如何获得每个情节,“Ave”“SD”和“ToT”是他们自己的颜色?如何通过“Sig”列添加注释来表示重要性?

2 个答案:

答案 0 :(得分:1)

您可以通过将数据重新整理为长(整洁)格式并使用factorplot来实现目标。

重塑:

dat = (
  pandas.DataFrame({
      'Labels':['v1','v2','c1','c2'],
      'Ave': [.2, .3, .5, .9],
      'SD': [0.02, 0.1, 0.04, 0.06],
      'Tot': [3, 4, 6, 8],
      'Sig': [0.05, 0.001, 0.0001, 0.05]
  }).set_index('Labels')
    .unstack()
    .reset_index()
    .rename(columns={
      'level_0': 'stat',
      0: 'result'
  })
)

print(dat.head(8))

  stat Labels  result
0  Ave     v1    0.20
1  Ave     v2    0.30
2  Ave     c1    0.50
3  Ave     c2    0.90
4   SD     v1    0.02
5   SD     v2    0.10
6   SD     c1    0.04
7   SD     c2    0.06

还有factorplot:

seaborn.factorplot('result', 'Labels', data=dat,
                   kind='bar', sharex=False,
                   hue='stat', hue_order=stats,
                   col='stat', col_order=stats)

enter image description here

问题在于条形是偏移的,因为使用hue告诉seaborn为每个y位置的不同类别腾出空间。

在下一个版本中,您可以说dodge=False以避免此偏移。

答案 1 :(得分:0)

Haven没有弄清楚如何用seaborn完成这项工作但是使用matplotlib这将会有效

import pandas as pd

dat = pd.DataFrame({
    'Labels':['v1','v2','c1','c2'],
    'Ave': [.2, .3, .5, .9],
    'SD': [0.02, 0.1, 0.04, 0.06],
    'Tot': [3, 4, 6, 8],
    'Sig':[0.05, 0.005, 0.0001, 0.05],
    'Sig_mask': [1,2,3,1],
})   

import matplotlib.pyplot as plt
fig = plt.figure()

# multiple plots 
ax1 = fig.add_subplot(131)

# horizontal bar plot and set color
ax1.barh(dat.index.values, dat['SD'], color='r', align='center')

# SET SPINES VISIBLE
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)

# SET X, Y LABELS
ax1.set(yticks=dat.index.values, yticklabels=dat.Labels.values)
ax1.set(xlabel='SD')

# ADD SIG NOTATION
for idx, val in enumerate(dat.SD.values):
    ax1.text(x=val+.003, y=idx, s='*'*dat.Sig_mask[idx], va='center')

# ADD SECOND PLOT
ax2 = fig.add_subplot(132)
# everything else much in the same manner, change color and data column


# ADD THIRD PLOT
ax3 = fig.add_subplot(133)
# same as above