Plotly:连续直方图颜色

Plotly: Continuous Histogram Color

我创建了一个图表,将随机游走的坐标显示为直方图。我想向 plot 函数添加一个属性,以查看直方图以连续颜色从浅蓝色(列表中的第一个直方图)到深蓝色(列表中的最后一个直方图)前进。有没有一种简单的方法可以做到这一点?

from plotly.graph_objs import Bar, Layout
from plotly import offline

from random_walk import RandomWalk


# Make a random walk.
rw = RandomWalk(50)
rw.fill_walk()

x_values = rw.x_values
y_values = rw.y_values

# Visualize the results.
data = [Bar(x=x_values, y=y_values)]

x_axis_config = {'title': 'Horizontal Coordinate'}
y_axis_config = {'title': 'Vertical Coordinate'}
my_layout = Layout(title='Results of a 1000 Steps Random Walk',
    xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, 
    filename='rw_visual_plotly.html')

class创建步骤:

from random import choice

class RandomWalk:
    """A class to generate random walks."""

    def __init__(self, num_points=5000):
        """Initialize attributes of a walk."""
        self.num_points = num_points

        # All walks start at (0, 0).
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        """Calculate all the points in the walk."""

        # Keep taking steps until the walk reaches the desired length.
        while len(self.x_values) < self.num_points:

            # Decide which direction to go and how far to go in that direction.
            x_direction = choice([-1, 1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([-1, 1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            # Reject moves that go nowhere.
            if x_step == 0 and y_step == 0:
                continue

            # Calculate the new position.
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)    

您可以使用 colour 库中的 range_to() 函数生成介于两种不同颜色(例如浅蓝色和深蓝色)之间的一系列颜色。

from plotly.graph_objs import Bar, Layout
from plotly import offline
from colour import Color
import numpy as np

# Make a random walk.
rw = RandomWalk(50)
rw.fill_walk()

x_values = np.array(rw.x_values)
y_values = np.array(rw.y_values)

x_values = x_values[np.argsort(x_values)]
y_values = y_values[np.argsort(x_values)]

# Visualize the results.
start_color = '#b2d8ff' # light blue
end_color = '#00264c' # dark blue

# list of colors between 'start_color' and 'end_color'
colorscale = [x.hex for x in list(Color(start_color).range_to(Color(end_color), 50))]

data = []

for i in range(len(x_values)):

    data.append(Bar(x=[x_values[i]], y=[y_values[i]], marker=dict(color=colorscale[i])))

x_axis_config = {'title': 'Horizontal Coordinate'}
y_axis_config = {'title': 'Vertical Coordinate'}

my_layout = Layout(title='Results of a 1000 Steps Random Walk', 
                   xaxis=x_axis_config, yaxis=y_axis_config, 
                   showlegend=False, barmode='stack')

offline.plot({'data': data, 'layout': my_layout}, filename='rw_visual_plotly.html')

请参阅 Plotly 社区论坛中的 this post

from plotly.graph_objs import Bar, Layout
from plotly import offline

# Make a random walk.
rw = RandomWalk(50)
rw.fill_walk()

x_values = rw.x_values
y_values = rw.y_values

# Visualize the results.
data = [Bar(x=x_values, y=y_values, marker={'color': x_values, 'colorscale': 'Blues'})]

x_axis_config = {'title': 'Horizontal Coordinate', 'linecolor': 'gray', 'mirror': True}
y_axis_config = {'title': 'Vertical Coordinate', 'linecolor': 'gray', 'mirror': True}

my_layout = Layout(title='Results of a 1000 Steps Random Walk', plot_bgcolor='white',
                   xaxis=x_axis_config, yaxis=y_axis_config)

offline.plot({'data': data, 'layout': my_layout}, filename='rw_visual_plotly.html')