(更新版本的情节的更新答案)
使用较新版本的 plotly,您可以指定dtick = 'M1'
在每个月初设置网格线。您还可以通过以下方式格式化月份的显示tickformat
:
片段 1
fig.update_xaxes(dtick="M2",
tickformat="%b\n%Y"
)
情节 1
如果您想每隔一个月设置一次网格线,只需更改"M1"
为"M2"
情节 2
完整代码:
# imports
import pandas as pd
import plotly.express as px
# data
df = px.data.stocks()
df = df.tail(40)
colors = px.colors.qualitative.T10
# plotly
fig = px.line(df,x = 'date',
y = [c for c in df.columns if c != 'date'],
template = 'plotly_dark',
color_discrete_sequence = colors,
title = 'Stocks',
)
fig.update_xaxes(dtick="M2",
tickformat="%b\n%Y"
)
fig.show()
旧解决方案:
如何设置网格线将完全取决于您想要显示的内容,以及在您尝试编辑设置之前如何构建图形。但是要获得问题中指定的结果,您可以这样做。
步骤1:
编辑fig['data'][series]['x']
中的每个系列fig['data']
。
第2步:
设置tickmode和ticktext:
go.Layout(xaxis = go.layout.XAxis(tickvals = [some_values]
ticktext = [other_values])
)
结果:
Jupyter Notebook 的完整代码:
# imports
import plotly
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import numpy as np
from IPython.display import HTML
from IPython.core.display import display, HTML
import copy
import plotly.graph_objs as go
# setup
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')
#%qtconsole --style vim
# Random data using cufflinks
df = cf.datagen.lines()
# create figure setup
fig = df.iplot(asFigure=True, kind='scatter',
xTitle='Dates',yTitle='Returns',title='Returns')
# create df1 to mess around with while
# keeping the source intact in df
df1 = df.copy(deep = True)
df1['idx'] = range(0, len(df))
# time variable operations and formatting
df1['yr'] = df1.index.year
df1['mth'] = df1.index.month_name()
# function to replace month name with
# abbreviated month name AND year
# if the month is january
def mthFormat(month):
dDict = {'January':'jan','February':'feb', 'March':'mar',
'April':'apr', 'May':'may','June':'jun', 'July':'jul',
'August':'aug','September':'sep', 'October':'oct',
'November':'nov', 'December':'dec'}
mth = dDict[month]
return(mth)
# replace month name with abbreviated month name
df1['mth'] = [mthFormat(m) for m in df1['mth']]
# remove adjacent duplicates for year and month
df1['yr'][df1['yr'].shift() == df1['yr']] = ''
df1['mth'][df1['mth'].shift() == df1['mth']] = ''
# select and format values to be displayed
df1['idx'][df1['mth']!='']
df1['display'] = df1['idx'][df1['mth']!='']
display = df1['display'].dropna()
displayVal = display.values.astype('int')
df_display = df1.iloc[displayVal]
df_display['display'] = df_display['display'].astype('int')
df_display['yrmth'] = df_display['mth'] + '<br>' + df_display['yr'].astype(str)
# set properties for each trace
for ser in range(0,len(fig['data'])):
fig['data'][ser]['x'] = df1['idx'].values.tolist()
fig['data'][ser]['text'] = df1['mth'].values.tolist()
fig['data'][ser]['hoverinfo']='all'
# layout for entire figure
f2Data = fig['data']
f2Layout = go.Layout(
xaxis = go.layout.XAxis(
tickmode = 'array',
tickvals = df_display['display'].values.tolist(),
ticktext = df_display['yrmth'].values.tolist(),
zeroline = False)#,
)
# plot figure with specified major ticks and gridlines
fig2 = go.Figure(data=f2Data, layout=f2Layout)
iplot(fig2)
一些重要的细节:
1. 灵活性和局限性iplot()
:
这种使用iplot()
和编辑所有这些设置的方法有点笨拙,但它在数据集中的列/变量的数量方面非常灵活,并且可以说比手动构建每个跟踪更可取,就像trace1 = go.Scatter()
为 df 中的每一列一样。
2. 为什么要编辑每个系列/轨迹?
如果您尝试跳过中间部分
for ser in range(0,len(fig['data'])):
fig['data'][ser]['x'] = df1['idx'].values.tolist()
fig['data'][ser]['text'] = df1['mth'].values.tolist()
fig['data'][ser]['hoverinfo']='all'
并尝试直接在整个情节上设置tickvals
和ticktext
,它将没有效果:
我认为这有点奇怪,但我认为这是由iplot()
.
3. 还缺少一件事:
为了使设置正常工作, 和 的结构分别是ticvals
和。这会导致 xaxis 悬停文本显示数据的位置,其中和为空:ticktext
[0, 31, 59, 90]
['jan<br>2015', 'feb<br>', 'mar<br>', 'apr<br>']
ticvals
ticktext
任何关于如何改进整个事情的建议都非常感谢。比我自己更好的解决方案将立即获得已接受答案状态!