情节:如何为x轴设置主要刻度线/网格线的值? [英] Plotly: How to set values for major ticks / gridlines for x-axis?

查看:321
本文介绍了情节:如何为x轴设置主要刻度线/网格线的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

此问题与 Plotly:如何检索主要刻度线和网格线的值?.对于 matplotlib ,这里也提出了类似的问题,但没有得到回答:

This question is related, but not identical, to Plotly: How to retrieve values for major ticks and gridlines?. A similar question has also been asked but not answered for matplotlib here: How do I show major ticks as the first day of each months and minor ticks as each day?

Plotly非常棒,也许困扰我的唯一事情是自动选择刻度线/网格线以及为x轴选择的标签,如下图所示:

Plotly is fantastic, and maybe the only thing that bothers me is the autoselection of ticks / gridlines and the labels chosen for the x-axis like in this plot:

情节1:

我认为这里自然要显示的是 每月的第一天 (取决于课程的期限).或者,甚至在每个刻度上都只是一个缩写的月份名称,例如'Jan'.由于所有月份的长度都不相同,因此我意识到了技术上甚至是视觉上的挑战.但是有人知道怎么做吗?

I think the natural thing to display here is the first of each month (depending ong the period of course). Or maybe even just an abreviateed month name like 'Jan' on each tick. I realize both the technical and even visual challenges due to the fact that all months are not of equal length. But does anyone know how to do this?

可复制的代码段:

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

# setup
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')

# Random data using cufflinks
df = cf.datagen.lines()
#df = df['UUN.XY']

fig = df.iplot(asFigure=True, kind='scatter',
               xTitle='Dates',yTitle='Returns',title='Returns')

iplot(fig)

推荐答案

解决方案:

如何设置网格线将完全取决于您要显示的内容,以及之前如何构建图形,然后尝试编辑设置.但是要获得问题中指定的结果,您可以这样做.

How to set the gridlines will depend entirely on what you'd like to display, and how the figure is built before you try to edit the settings. But to obtain the result specified in the question, you can do it like this.

第一步:

fig['data']中的每个系列编辑fig['data'][series]['x'].

第二步:

在以下位置设置tickmode和ticktext:

set tickmode and ticktext in:

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()的灵活性和局限性:

1. Flexibility and limitations with iplot():

这种使用iplot()并编辑所有设置的方法有点笨拙,但是在数据集中的列/变量数方面非常灵活,并且可以说最好像每个trace1 = go.Scatter()那样手动构建每个跟踪以及df中的每一列.

This approach with iplot() and editing all those settings is a bit clunky, but it's very flexible with regards to the number of columns / variables in the dataset, and arguably preferable to building each trace manually like trace1 = go.Scatter() for each and every column in the df.

2.为什么您必须编辑每个系列/轨迹?

如果您尝试跳过中间部分

If you try to skip the middle part with

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'

并尝试直接在整个图上设置tickvalsticktext,它将无效:

and try to set tickvals and ticktext directly on the entire plot, it will have no effect:

我认为这有点奇怪,但是我认为这是由iplot()发起的一些基础设置引起的.

I think that's a bit weird, but I think it's caused by some underlying settings initiated by iplot().

3.仍然缺少一件事:

为了使设置正常工作,ticvalsticktext的结构分别为[0, 31, 59, 90]['jan<br>2015', 'feb<br>', 'mar<br>', 'apr<br>'].这会导致x轴行悬停文本显示ticvalsticktext为空的数据的位置:

In order fot thie setup to work, the structure of ticvals and ticktext is [0, 31, 59, 90] and ['jan<br>2015', 'feb<br>', 'mar<br>', 'apr<br>'], respectively. This causes the xaxis line hovertext show the position of the data where ticvals and ticktext are empty:

任何有关如何改善整体效果的建议均受到高度赞赏.比我自己的解决方案更好的解决方案将立即获得 已接受答案 状态!

Any suggestions on how to improve the whole thing is highly appreciated. Better solutions than my own will instantly receive Accepted Answer status!

这篇关于情节:如何为x轴设置主要刻度线/网格线的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆