【问题标题】:Cufflinks module of plotly do not show z axis for scatter plotplotly 的袖扣模块不显示散点图的 z 轴
【发布时间】:2017-10-07 18:13:44
【问题描述】:

我正在尝试使用cufflink 一个由plotlypandas 组成的包装库来绘制带有z 轴的散点图。我注意到iplotz 参数,但我无法让它工作。

from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
init_notebook_mode()

import cufflinks as cf
cf.go_offline()

df = cf.datagen.lines(3,columns=['a','b','c'])

df.iplot(x='a', y='b', z='c', kind='scatter', mode='markers')

但是z轴不显示。

【问题讨论】:

    标签: python python-3.x pandas plotly


    【解决方案1】:

    我刚刚发现查看源代码,z 参数没有被考虑到 kind=scatter 作为 kwarg。

    我只是分享一个我发现使用 plotly 来满足我需求的解决方案。如果有人设法找到一个更快的袖扣解决方案,我会非常高兴,否则这个就可以了。它还具有正确显示时间尺度的优点

    import pandas as pd
    import plotly.graph_objs as go
    from plotly.offline import iplot
    
    
    def py_scatter_by_z(x, y, z=None, x_title=None, y_title=None, mode='markers', colorscale='Jet', showscale=True, size=10,
                        line_color='black',
                        line_width=1, date_format="%b'%y", n_ticks=8, opacity=.5, scatter_kwargs=dict(), **layout_kwargs):
        '''
        Plots a scatter plot between two variables x and y and colors each point according to a variable z.
    
        Plotly and genereralized version of plot_scatter_by_time.
    
        Args:
            x (1D-Series | list | 1-D Array): values of x-axis. 
            y (1D-Series | list | 1-D Array): values of y-axis.
            z (1D-Series | list | 1-D Array): values of z-axis used for colorscale. Could be Numeric or dates. 
            x_title (str): label of x_axis.
            y_title (str): label of y_axis.
            mode (str): Scatter mode, i.e. "markers" or "lines+markers". Default is markers 
            colorscale (str): Colorscale to use to color the points. 
                        See plotly colorscale/matplotlib colormap. 
                        Default is "Jet".
            showscale (bool): Show colorbar if True (default). 
            size (int): size of the markers. Default is 10. 
            line_color (str): color of edge line of markers. Default is "black".
            line_width (int): width of edge line of markers. Default is 1.
            date_format (str): format of the   
            n_ticks (int): Number of ticks to display in the colorbar.  
            opacity (float between 0 and 1): opacity/transparency of filled markers. Default is 0.5.
            scatter_kwargs (dict): dictionary passed as kwargs for scatter. Default is empty dictionary. 
            **layout_kwargs: kwargs of the function, used as layout kwargs.
    
        Returns: dictionary representing a plotly figure.
    
        '''
    
        # Basic trace
        trace = go.Scatter(
            x=x,
            y=y,
            mode=mode,
        )
    
        layout = go.Layout(xaxis=dict(title=x_title), yaxis=dict(title=y_title))
        layout.update(**layout_kwargs)
    
        # Coloring points
        if z is not None:
            z_all_dates = pd.Series(index=z).index.is_all_dates
    
            if z_all_dates:
                # Special treatment if z is a datetime vector
                color = pd.to_numeric(z)
                step = int(len(z) / n_ticks)
                z = list(z)
                ticktext = [date.strftime(date_format) for date in z[1::step]]
                tickvals = list(color)[1::step]
                colorbar = dict(nticks=n_ticks,
                                tickvals=tickvals,
                                ticktext=ticktext)
            else:
                color = z
                colorbar = dict()
    
            marker = {'marker': dict(size=size, color=color, colorscale=colorscale,
                                     showscale=showscale, opacity=opacity, colorbar=colorbar)}
            trace.update({'text': z})
    
        else:
            marker = {'marker': dict(size=size)}
    
        # Construct and plot figure
        marker['marker'].update({'line': {'color': line_color, 'width': line_width}})
        trace.update(marker)
        trace.update(**scatter_kwargs)
        data = [trace]
        fig = go.Figure(data=data, layout=layout)
        iplot(fig)
    
        return fig
    
    
    from plotly.offline import init_notebook_mode, iplot
    import plotly.graph_objs as go
    init_notebook_mode()
    
    import cufflinks as cf
    cf.go_offline()
    
    df = cf.datagen.lines(3,columns=['a','b','c'])
    df.index = pd.to_datetime(df.index) # Example with a time scale
    py_scatter_by_z(df['a'], df['b'], df.index)
    

    【讨论】:

      【解决方案2】:

      散点图只有 x 轴和 y 轴。将kind 设置为scatter3d 会添加z 轴。

      from plotly.offline import init_notebook_mode, iplot
      import plotly.graph_objs as go
      init_notebook_mode()
      
      import cufflinks as cf
      cf.go_offline()
      
      df = cf.datagen.lines(3,columns=['a','b','c'])
      
      df.iplot(x='a', y='b', z='c', kind='scatter3d', mode='markers')
      

      如果您想为绘图添加第三个维度,您还可以使用散点图并将信息添加到您的颜色中。在这种情况下,不使用袖扣更容易。

      import plotly
      plotly.offline.init_notebook_mode()
      import cufflinks as cf
      cf.go_offline()
      
      df = cf.datagen.lines(3, columns=['a','b','c'])
      trace1 = plotly.graph_objs.Scatter(x=df.a, 
                                         y=df.b, 
                                         marker=dict(color=df.c,
                                                     showscale=True), 
                                         mode='markers')
      fig = plotly.graph_objs.Figure(data=[trace1])
      plotly.offline.iplot(fig)
      

      【讨论】:

      • 感谢您的回答,问题是 3d 绘图不符合我的需求。我在回答中详细说明了我期望通过 z 比例散布的示例。它更像是一张热图,但没有丑陋的方块。
      • @MCMZL:查看更新的答案以获取替代解决方案。
      【解决方案3】:
      # 1st create a data frame with 3 columns(I have taken a random data frame here)
      train_data.head(5) #check the data frame
      #plot the 3d scatter plot
      train_data.iplot(kind = 'scatter3d',x='a',y='b',z='c')#here 'a','b' and 'c' 
      are three columns of the data frame  
      [3d scatter plot within two lines of code][1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        • 1970-01-01
        • 2021-05-23
        • 2021-04-22
        • 1970-01-01
        • 2021-02-07
        • 2020-10-19
        相关资源
        最近更新 更多