如何防止 Matplotlib 将 x-axis 上的时间序列数据更改为 1970 年代?
How to prevent Matplotlib from changing time series data on x-axis to 1970s?
我正在尝试使用 Seaborn(和 Matplotlib)使用 python 从 pandas 数据框中绘制数据。我将日期设置为数据框中的索引值,从 2016-02-03 开始到当前日期结束。这些值是日期时间类型(不是字符串)。无论我尝试什么,当我绘制我拥有的数据图表时,它都会更改日期并一直追溯到 1970 年,而不是我拥有的日期。非常感谢任何帮助。
import matplotlib.pyplot as plt
import requests
import os
import pandas as pd
import json
from datetime import *
from percent import change
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource
from bokeh.models.tools import HoverTool
import numpy as np
import seaborn as sns
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
#constants
daily = "TIME_SERIES_DAILY"
symbols = ["COIN"]
COLOR = sns.color_palette('Set2')[4]
currentdate = date.today()
lastweek = currentdate - timedelta(days=7)
lastyear = currentdate - timedelta(days=364)
lastyear = str(lastyear)
currentdate = str(currentdate)
api_key = REDACTED
base_url = 'https://www.alphavantage.co/query?'
params = {'function': daily,
'outputsize': 'full',
'symbol': symbols[0],
'horizon': '3month',
'datatype': 'csv',
'apikey': api_key}
response = requests.get(base_url, params = params) #.json is same as json.loads()
#response_dict = response.json()
with open('eurusd.csv', 'wb') as file:
file.write(response.content)
sns.set(style="ticks", context="talk")
plt.style.use("dark_background")
df = pd.read_csv("eurusd.csv", parse_dates = True)
df.set_index('timestamp', inplace = True)
df = df.iloc[::-1] #flips
plt.rc('axes', titlesize=18) # fontsize of the axes title
plt.rc('axes', labelsize=14) # fontsize of the x and y labels
plt.rc('xtick', labelsize=13) # fontsize of the tick labels
plt.rc('ytick', labelsize=13) # fontsize of the tick labels
#plt.rc('legend', fontsize=13) # legend fontsize
plt.rc('font', size=10) # controls default text sizes
plt.figure(figsize=(8,5), tight_layout=True)
a = sns.lineplot(data = df['close'], color=sns.color_palette('Set2')[4],linewidth = 2)
#graph extras
sns.despine()
plt.xticks(rotation = 45, ha = 'right')
plt.xticks([500,1000]) # to replace with specific name: plt.xticks([500,1000], [name1, name2 etc])
a.spines['left'].set_color(COLOR)
a.spines['bottom'].set_color(COLOR)
a.xaxis.label.set_color(COLOR)
a.yaxis.label.set_color(COLOR)
a.tick_params(axis='x', colors= COLOR)
a.tick_params(axis='y', colors=COLOR)
a.set(xlabel=None)
a.set(ylabel=None)
a.set_title('Stock Chart', color = COLOR)
for tick_label in a.axes.get_yticklabels():
tick_label.set_color(sns.color_palette('Set2')[4])
for tick_label in a.axes.get_xticklabels():
tick_label.set_color(sns.color_palette('Set2')[4])
a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.show()
地块图片
CSV 数据的前几行:
2016-02-03 18.00 18.88 16.0000 18.20 4157947
2016-02-04 18.26 19.42 17.5725 18.50 469941
2016-02-05 18.84 18.88 17.5200 17.60 220160
2016-02-08 17.52 18.00 15.7200 15.85 372112
2016-02-09 15.50 15.50 12.7482 12.81 744115
运行 您的最新版本示例似乎使用了 x-axis:
的正确日期
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO
df_str = '''timestamp open close high low volume
2016-02-03 18.00 18.88 16.0000 18.20 4157947
2016-02-04 18.26 19.42 17.5725 18.50 469941
2016-02-05 18.84 18.88 17.5200 17.60 220160
2016-02-08 17.52 18.00 15.7200 15.85 372112
2016-02-09 15.50 15.50 12.7482 12.81 744115'''
df = pd.read_csv(StringIO(df_str), delim_whitespace=True)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
sns.lineplot(data=df, x='timestamp', y='close', ax=ax1)
sns.lineplot(data=df.set_index('timestamp')['close'], ax=ax2)
由于日期列表较长,因此仅显示年份或 year-month:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame({'timestamp': pd.date_range('2016-02-03', '2022-02-03')})
df['close'] = np.random.normal(0.02, 1, len(df)).cumsum() + 20
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 5))
sns.lineplot(data=df, x='timestamp', y='close', ax=ax1)
sns.lineplot(data=df.iloc[:len(df) // 2], x='timestamp', y='close', ax=ax2)
plt.tight_layout()
plt.show()
我正在尝试使用 Seaborn(和 Matplotlib)使用 python 从 pandas 数据框中绘制数据。我将日期设置为数据框中的索引值,从 2016-02-03 开始到当前日期结束。这些值是日期时间类型(不是字符串)。无论我尝试什么,当我绘制我拥有的数据图表时,它都会更改日期并一直追溯到 1970 年,而不是我拥有的日期。非常感谢任何帮助。
import matplotlib.pyplot as plt
import requests
import os
import pandas as pd
import json
from datetime import *
from percent import change
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource
from bokeh.models.tools import HoverTool
import numpy as np
import seaborn as sns
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
#constants
daily = "TIME_SERIES_DAILY"
symbols = ["COIN"]
COLOR = sns.color_palette('Set2')[4]
currentdate = date.today()
lastweek = currentdate - timedelta(days=7)
lastyear = currentdate - timedelta(days=364)
lastyear = str(lastyear)
currentdate = str(currentdate)
api_key = REDACTED
base_url = 'https://www.alphavantage.co/query?'
params = {'function': daily,
'outputsize': 'full',
'symbol': symbols[0],
'horizon': '3month',
'datatype': 'csv',
'apikey': api_key}
response = requests.get(base_url, params = params) #.json is same as json.loads()
#response_dict = response.json()
with open('eurusd.csv', 'wb') as file:
file.write(response.content)
sns.set(style="ticks", context="talk")
plt.style.use("dark_background")
df = pd.read_csv("eurusd.csv", parse_dates = True)
df.set_index('timestamp', inplace = True)
df = df.iloc[::-1] #flips
plt.rc('axes', titlesize=18) # fontsize of the axes title
plt.rc('axes', labelsize=14) # fontsize of the x and y labels
plt.rc('xtick', labelsize=13) # fontsize of the tick labels
plt.rc('ytick', labelsize=13) # fontsize of the tick labels
#plt.rc('legend', fontsize=13) # legend fontsize
plt.rc('font', size=10) # controls default text sizes
plt.figure(figsize=(8,5), tight_layout=True)
a = sns.lineplot(data = df['close'], color=sns.color_palette('Set2')[4],linewidth = 2)
#graph extras
sns.despine()
plt.xticks(rotation = 45, ha = 'right')
plt.xticks([500,1000]) # to replace with specific name: plt.xticks([500,1000], [name1, name2 etc])
a.spines['left'].set_color(COLOR)
a.spines['bottom'].set_color(COLOR)
a.xaxis.label.set_color(COLOR)
a.yaxis.label.set_color(COLOR)
a.tick_params(axis='x', colors= COLOR)
a.tick_params(axis='y', colors=COLOR)
a.set(xlabel=None)
a.set(ylabel=None)
a.set_title('Stock Chart', color = COLOR)
for tick_label in a.axes.get_yticklabels():
tick_label.set_color(sns.color_palette('Set2')[4])
for tick_label in a.axes.get_xticklabels():
tick_label.set_color(sns.color_palette('Set2')[4])
a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.show()
地块图片
CSV 数据的前几行:
2016-02-03 18.00 18.88 16.0000 18.20 4157947
2016-02-04 18.26 19.42 17.5725 18.50 469941
2016-02-05 18.84 18.88 17.5200 17.60 220160
2016-02-08 17.52 18.00 15.7200 15.85 372112
2016-02-09 15.50 15.50 12.7482 12.81 744115
运行 您的最新版本示例似乎使用了 x-axis:
的正确日期import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO
df_str = '''timestamp open close high low volume
2016-02-03 18.00 18.88 16.0000 18.20 4157947
2016-02-04 18.26 19.42 17.5725 18.50 469941
2016-02-05 18.84 18.88 17.5200 17.60 220160
2016-02-08 17.52 18.00 15.7200 15.85 372112
2016-02-09 15.50 15.50 12.7482 12.81 744115'''
df = pd.read_csv(StringIO(df_str), delim_whitespace=True)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
sns.lineplot(data=df, x='timestamp', y='close', ax=ax1)
sns.lineplot(data=df.set_index('timestamp')['close'], ax=ax2)
由于日期列表较长,因此仅显示年份或 year-month:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame({'timestamp': pd.date_range('2016-02-03', '2022-02-03')})
df['close'] = np.random.normal(0.02, 1, len(df)).cumsum() + 20
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 5))
sns.lineplot(data=df, x='timestamp', y='close', ax=ax1)
sns.lineplot(data=df.iloc[:len(df) // 2], x='timestamp', y='close', ax=ax2)
plt.tight_layout()
plt.show()