matplotlib散布c = date

时间:2017-07-21 11:19:20

标签: pandas matplotlib

如何使用x轴上的x,y轴上的值(每行一行)和 date

values = [[0.2, 3.1, 17.4, 28.9, 57.7, 76.9, 82.8, 87.6, 92.4, 98.9, 100.0],
          [0.2, 2.1, 15.5, 26.0, 54.2, 75.6, 82.1, 87.4, 92.4, 98.9, 100.0]]

x = [0.1, 0.2, 0.315, 0.4, 0.63, 1, 1.25, 1.6, 2, 3.15, 4]

dates = pd.date_range(start='2017-07-01', freq='D', periods=2)

data = pd.DataFrame(data=values, columns=x)

data['dates'] = dates

编辑:抱歉没有准确。

是否可以使用数据[x] .T.plot(kind =' line',legend = False)根据时间戳列设置线条的颜色。

如果无法做到这一点,请如何设置" c"在plt.scatter中为一个Timestamps数组?

编辑:情节应该如下所示,但应该有一个颜色条而不是一个图例 enter image description here

1 个答案:

答案 0 :(得分:0)

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

# create test data with a structure similar to the real data
x_values = np.linspace(1, 10, 8)
dat = np.random.randn(100, 8)
df = pd.DataFrame(data=np.abs(dat), columns=x_values)
df = df.cumsum(axis=1)
df = df.divide(df.max(axis=1), axis='index')

# create discontinuos date range and add it to data frame
dates = pd.date_range(start=('2016-01-01'), end=('2017-05-01'), freq='D')
dates = dates[(dates < '2016-07-01') | (dates > '2017-03-01')]
df['date'] = sorted(random.sample(dates.date.tolist(), 100))

# create a dataframe with a continous date range (see df) and corresponding colors
drange = pd.date_range(start=df['date'].min(), end=df['date'].max(), freq='D')
colors = iter(plt.cm.jet(np.linspace(0, 1, drange.shape[0])))
cdf = pd.DataFrame(data=np.array([drange.date, list(colors)]).T, columns=['date', 'colors'])

# and merge colors to data
data = pd.merge(df, cdf)

# plot all data row by row with color of lines
# matching the date columns

fig, ax = plt.subplots()

for idx in data.index:
    ax.plot(x_values, data.loc[idx, x_values],
            linestyle='-', alpha=0.75, 
            color=data.loc[idx, 'colors'],
            label=data.loc[idx, 'date'])

# reduce entries of legend
handles, labels = ax.get_legend_handles_labels()
entries = int(data.shape[0]/10)
handles = handles[::entries]
labels = labels[::entries]
ax.legend(handles, labels)