2017-07-18 114 views
4

我在熊貓數據框中存儲了一些數據。另外,我正在使用matplotlib創建顯示數據的圖。請看看這個漂亮的圖片:matplotlib熊貓圖中的附加「軸像」圖

plot I want

紅線表示對應於x軸點的一些值。它只是數據框中的一列。我想添加額外的註釋,將x軸點分類。這些類別作爲附加列存儲在原始數據框中。它不必像圖片中那樣完全一樣。

目標是以某種方式顯示x軸範圍分類。什麼是添加這種註釋的聰明和優雅的方式?

+0

如何在數據框中指定應標明範圍? – ImportanceOfBeingErnest

+0

有一列有值,例如'['a','a',NaN,'a','b'....]',因此每個索引都有相應的類別。 –

回答

3
import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 

# Create sample data 
df = pd.DataFrame({'Data': [np.sin(i) + 3 for i in np.arange(1, 11, 0.1)], 
        'Annotation': ['A'] * 10 + ['B'] * 20 + [np.nan] * 10 + 
           ['C'] * 10 + ['D'] * 10 + [np.nan] * 20 + 
           ['D'] * 20}) 
# Get unique annotations 
annotation_symbols = [i for i in df['Annotation'].unique() if not pd.isnull(i)] 
# Transform each unique text annotation into a new column, 
# where ones represent the corresponding annotation being 'active' and 
# NaNs represent the corresponding annotation being 'inactive' 
df = pd.concat([df, pd.get_dummies(df['Annotation']).replace(0, np.nan)]) 

plt.style.use('ggplot') # Let's use nicer style 
ax = plt.figure(figsize=(7, 5)).add_subplot(111) 
df.plot.line(x=df.index, y='Data', ax=ax) 
df.plot.line(x=df.index, y=annotation_symbols, ax=ax) 

製作圖:

enter image description here