def __add_const_trend_trace(self, trend_name: str, trend: PlotlyTrendLine, fig: pgo.Figure): all_series = {**self.series, **self.averages} if trend.related_series_id not in all_series: raise InvalidTrendLine(f"Missing related series: {trend.related_series_id}") if trend.constant is None: raise InvalidTrendLine(f"Constant must be specified to draw const trendline") series = all_series[trend.related_series_id] xs_range = series.data[series.x_field] xs = np.linspace(xs_range.min(), xs_range.max(), 10) ys = np.full(10, trend.constant) trace = pgo.Scatter( x=xs, y=ys, name=trend_name, mode='lines', line={ 'dash': 'dash', 'color': 'red', 'width': 0.4, } ) fig.add_trace(trace)
def __add_ml_linear_trend_trace(self, trend_name: str, trend: PlotlyTrendLine, fig: pgo.Figure): all_series = {**self.series, **self.averages} if trend.related_series_id not in all_series: raise InvalidTrendLine(f"Missing related series: {trend.related_series_id}") series = all_series[trend.related_series_id] xs = np.array(series.data[series.x_field]).reshape(-1, 1) ys = np.array(series.data[series.y_field]).reshape(-1, 1) model = LinearRegression() model.fit(xs, ys) xs_predict = np.linspace(xs.min(), xs.max(), 100).reshape(-1, 1) ys_predict = model.predict(xs_predict) trace = pgo.Scatter( x=xs_predict.reshape(1, -1)[0], y=ys_predict.reshape(1, -1)[0], name=trend_name, mode='lines', line={ 'dash': 'dash', 'color': 'red', } ) fig.add_trace(trace)
def __add_trace(self, series: PlotSeries, fig: pgo.Figure): show_error_y = self.properties.show_error_bars and \ series.y_err_field is not None and \ series.y_err_field in series.data.columns trace_mode = { PlotSeriesKind.SCATTER: 'markers', PlotSeriesKind.SCATTERLINE: 'markers+lines', PlotSeriesKind.LINE: 'lines', }[self.properties.default_series_kind] trace = pgo.Scatter( name=series.series_info.series_name, mode=trace_mode, x=series.data[series.x_field], y=series.data[series.y_field], error_y=None if not show_error_y else { 'type': 'data', 'visible': series.y_err_field is not None, 'array': series.data[series.y_err_field], 'color': PlotUtils.series_color_hex(series.series_info.series_id), 'thickness': 0.5, 'width': 1, }, marker={ 'symbol': 'circle', }, line={ 'color': PlotUtils.series_color_hex(series.series_info.series_id), } ) fig.add_trace(trace)
def build(z: List[List[float]], scale: Union[str, List[List[Union[float, str]]]], path: str): """ Тут будується графік, після чого зображення зберігається у файл. """ figure = Figure() figure.add_trace( Heatmap(z=z, zmin=0, zmax=1, colorscale=scale, showscale=False)) figure.update_layout(showlegend=False, plot_bgcolor='white', margin={ 't': 0, 'r': 0, 'b': 0, 'l': 0 }) figure.update_xaxes(showticklabels=False, showgrid=False, showline=False, zeroline=False) figure.update_yaxes(scaleanchor='x', scaleratio=1, showticklabels=False, showgrid=False, showline=False, zeroline=False) figure.write_image(path, width=1600, height=800)
def generate_line_plots( y_matrix: np.ndarray, lap_time_matrix: np.ndarray, figure: go.Figure, ) -> None: """ Given a matrix of lap times and a matrix to plot on the y-axis, this function will add line plots to the figure. Each line could represent, e.g., the distance to the first driver or the position of the driver Parameters ---------- y_matrix Each row of this matrix will become a separate line in the figure lap_time_matrix A matrix with the lap times for each driver figure The figure to which the lines should be added Returns ------- """ for driver_idx in range(lap_time_matrix.shape[0]): line_plot = go.Scatter( x=list(range(lap_time_matrix.shape[1])), y=y_matrix[driver_idx, :], name=f'Driver {driver_idx}', marker_size=1, ) figure.add_trace(line_plot)
def plot(self, fig: go.Figure) -> go.Figure: width = 2 color1 = 'rgba(46, 134, 193, 0.5)' color2 = 'rgba(40, 180, 99, 0.5)' color3 = 'rgba(136, 78, 160, 0.5)' position = (1, 1) macd_, signal, hist = self.result #fig.add_trace(go.Scatter(x=self.data['date'], # y=macd_, # mode='lines', # name='macd', # line=dict(color=color1, width=width) # ), # row=position[0], col=position[1] # ) fig.add_trace(go.Scatter(x=self.data['date'], y=signal, mode='lines', name='macd_signal', line=dict(color=color2, width=width)), row=position[0], col=position[1]) fig.add_trace(go.Bar( x=self.data['date'], y=hist, marker_color=color3, name='macd_hist', ), row=position[0], col=position[1]) return fig
def countries_shifted_scatters(self, countries: list, column: str, threshold: int = 100, mode: str = None, showlegend: bool=True) -> Figure: countries_df = self.countries_dataframe(countries=countries, column=column, threshold=threshold) countries_df.dropna(axis="index", how="all", inplace=True) countries_df = countries_df.apply(lambda x: Series(x.dropna().values)) engine = inflect.engine() fig = Figure() for country in countries: fig.add_trace( Scatter( x=countries_df.index, y=countries_df[country], name=country, mode=mode, line_color=self.color.get(country, "black"), opacity=0.9, showlegend=showlegend, ) ) fig.update_layout(yaxis_type="log") fig.update_layout(title_text="Days since \"{}\" column above {} {}".format(column, threshold, engine.plural_noun("occurence", threshold))) return fig
def countries_scatters(self, countries: list, column: str, mode: str=None, showlegend: bool=True) -> Figure: fig = Figure() ratio_re = re.compile(r"(?x: \b Ratio \b )") daily_re = re.compile(r"(?x: \b Daily \b )") if ratio_re.search(column) is not None: fig.update_layout(yaxis=dict(tickformat="%.format.%3f")) for country in countries: country_df = self.main_df.loc[[country]].reset_index(level=0, drop=True) if daily_re.search(column) is not None: country_df = country_df[1:] fig.add_trace( Scatter( x=country_df.index, y=country_df[column], name=country, mode=mode, line_color=self.color.get(country, "black"), opacity=0.9, showlegend=showlegend, ) ) fig.update_layout(title_text=column) return fig
def whatevers_bar_chart(self, whatever: str="total") -> Figure: """ Stacked bar chart of total active, deaths and recovered values """ columns = ["active", "deaths", "recovered"] dates = self.main_df.reset_index()["Date"] color = { "active": "#ffb347", # Pastel Orange "deaths": "#ff6961", # Pastel Red "recovered": "#77dd78", # Pastel Green } engine = inflect.engine() fig = Figure() for column in columns: name = "{} {}".format(whatever.capitalize(), column.capitalize()) ys = self.main_df[name].sum(level=1) if whatever == "daily": ys = ys[1:] fig.add_trace(Bar(name=name, x=dates, y=ys, marker={"color": color[column]})) fig.update_layout(barmode="stack", title_text=engine.plural(whatever).capitalize()) fig.update_traces(marker_line_width=0) return fig
def plot(self, fig: go.Figure) -> go.Figure: width = 2 color1 = 'rgba(46, 134, 193, 0.5)' position = (1, 1) rsi = self.result fig.add_trace(go.Scatter(x=self.data['date'], y=rsi, mode='lines', name='rsi', line=dict(color=color1, width=width)), row=position[0], col=position[1]) fig.add_shape(type="line", x0=self.data['date'].min(), y0=30, x1=self.data['date'].max(), y1=30, line=dict(color=color1, width=width, dash="dot"), row=position[0], col=position[1]) fig.add_shape(type="line", x0=self.data['date'].min(), y0=70, x1=self.data['date'].max(), y1=70, line=dict(color=color1, width=width, dash="dot"), row=position[0], col=position[1]) return fig
def run_and_plot_single_fit_comparison(fig: go.Figure, data: Data1D) -> go.Figure: """ Runs both Args: fig (): data (): Returns: """ i_sense_fit = fit_single_transition(data, fit_with='i_sense', initial_params=None) nrg_params = get_initial_params(data, 'nrg') nrg_params['g'].value = 0.001 nrg_params['g'].vary = False nrg_params['occ_lin'].vary = False nrg_fit = fit_single_transition(data, fit_with='nrg', initial_params=nrg_params) for fit, name in zip([i_sense_fit, nrg_fit], ['i_sense', 'NRG']): fig.add_trace( p1d.trace(x=data.x, data=fit.eval_fit(x=data.x), name=name, mode='lines')) print(i_sense_fit) print(nrg_fit) return fig
def add_area_trace( fig: go.Figure, x_series: list, y_series: list, name: str, color: str, row: int, showlegend: bool = True, linewidth: float = 0.2, ) -> go.Figure: """Adding single area trace to subplot""" fig.add_trace( go.Scatter( x=x_series, y=y_series, hoverinfo="text+x+y", hoveron="fills", mode="lines", # fill="tonexty", # fillcolor=color, line=dict(width=linewidth, color=color), name=name, text=name, stackgroup="one", legendgroup="Ctrl Modes", showlegend=showlegend, ), row=row, col=1, )
def plot_traces(self, fig: go.Figure, data: pd.DataFrame, x: str, y: str, hue: str, row: int, col: int, mode: str = 'lines') -> go.Figure: """ The goal is create a similar behavior as plotly express or seaborn. This function will take x, y, and hue column names and use them to layer the correct scatter plots together. :param fig: ploty fig where this plot (or these traces) will be places :param data: dataframe containing all the columns listed in x, y, and hue :param x: column name of x-axis :param y: column name of y-axis :param hue: column name of category column :param row: the row number inside the fig where the plot will be located :param col: the column number inside the fig where the plot :param mode: plotly.graph_objects.Scatter mode value :return: plot fig with plot added s """ for n, category in enumerate(data[hue].unique()): temp = data[data[hue] == category] chart = go.Scatter(x=temp[x], y=temp[y], mode='lines', name=category, marker_color=px.colors.sequential.Plasma[n]) fig.add_trace(chart, row=row, col=col) return fig
def _add_camera_trace( fig: go.Figure, cameras: CamerasBase, trace_name: str, subplot_idx: int, ncols: int, camera_scale: float, ): """ Adds a trace rendering a Cameras object to the passed in figure, with a given name and in a specific subplot. Args: fig: plotly figure to add the trace within. cameras: the Cameras object to render. It can be batched. trace_name: name to label the trace with. subplot_idx: identifies the subplot, with 0 being the top left. ncols: the number of sublpots per row. camera_scale: the size of the wireframe used to render the Cameras object. """ cam_wires = get_camera_wireframe(camera_scale).to(cameras.device) cam_trans = cameras.get_world_to_view_transform().inverse() cam_wires_trans = cam_trans.transform_points(cam_wires).detach().cpu() # if batch size is 1, unsqueeze to add dimension if len(cam_wires_trans.shape) < 3: cam_wires_trans = cam_wires_trans.unsqueeze(0) nan_tensor = torch.Tensor([[float("NaN")] * 3]) all_cam_wires = cam_wires_trans[0] for wire in cam_wires_trans[1:]: # We combine camera points into a single tensor to plot them in a # single trace. The NaNs are inserted between sets of camera # points so that the lines drawn by Plotly are not drawn between # points that belong to different cameras. all_cam_wires = torch.cat((all_cam_wires, nan_tensor, wire)) x, y, z = all_cam_wires.detach().cpu().numpy().T.astype(float) row, col = subplot_idx // ncols + 1, subplot_idx % ncols + 1 fig.add_trace( go.Scatter3d( # pyre-ignore [16] x=x, y=y, z=z, marker={"size": 1}, name=trace_name), row=row, col=col, ) # Access the current subplot's scene configuration plot_scene = "scene" + str(subplot_idx + 1) current_layout = fig["layout"][plot_scene] # flatten for bounds calculations flattened_wires = cam_wires_trans.flatten(0, 1) verts_center = flattened_wires.mean(0) max_expand = (flattened_wires.max(0)[0] - flattened_wires.min(0)[0]).max() _update_axes_bounds(verts_center, max_expand, current_layout)
def build_mse_dependency( distribution_name: str, thetas: List[float], n_moments: int, n_samples: int, n_runs: int ) -> Figure: figure = Figure() figure.update_layout(title=f"Dependency between moment and MSE for {distribution_name} distribution") figure.update_xaxes(title="k") figure.update_yaxes(title="MSE") for theta in thetas: experiment = Experiment(distribution_name, theta) mse = experiment.run(n_moments, n_samples, n_runs) figure.add_trace(create_mse_scatter(mse, distribution_name, theta)) return figure
def add_to_plot( fig: go.Figure, y: List[float], y_labels: Optional[List[str]] = None, y_err: Optional[List[float]] = None, practical_maximum: Optional[float] = None, label: Optional[str] = None, index: int = 0): color = QUALITATIVE_COLORS[index % len(QUALITATIVE_COLORS)] rgb_ints = [str(int(x.strip(" "))) for x in color[4:][:-1].split(",")] new_color = f"rgba({','.join(rgb_ints + ['0.2'])})" custom_data: Optional[List[Any]] = None hover_template = None if y_labels: if y_err: custom_data: List[Any] = list(zip(y_labels, y_err)) hover_template = '<b>%{y:.3f} +- %{customdata[1]:.3f}</b><br>%{customdata[0]}' else: custom_data = y_labels hover_template = '<b>%{y:.3f}</b><br>%{customdata}' # Error range x = list(range(1, len(y) + 1)) if y_err: y_upper = [m + e for m, e in zip(y, y_err)] y_lower = [m - e for m, e in zip(y, y_err)] fig.add_trace(go.Scatter( x=x + x[::-1], y=y_upper + y_lower[::-1], fill='toself', fillcolor=new_color, line_color='rgba(255,255,255,0)', showlegend=False, name=label, hoverinfo='skip', legendgroup=label, )) # Mean line fig.add_trace(go.Scatter( x=x, y=y, customdata=custom_data, hovertemplate=hover_template, line_color=color, showlegend=True, name=label, legendgroup=label, )) fig.update_traces(mode='lines') # Make serif fig.update_layout(font=dict( family="serif", )) return fig
def add_indicator(data: pd.DataFrame, fig: go.Figure, name: str, color: str = 'rgba(46, 134, 193, 0.5)') -> go.Figure: width = 2 fig.add_trace(go.Scatter(x=data['date'], y=data[name], mode='lines', name=name, line=dict(color=color, width=width)), row=2, col=1) return fig
def plot(self, fig: go.Figure) -> go.Figure: color = 'rgba(136, 78, 160, 0.5)' position = (1, 1) ao = self.result fig.add_trace(go.Bar( x=self.data['date'], y=ao, marker_color=color, name='awesome oscillator', ), row=position[0], col=position[1]) return fig
def plot(self, fig: go.Figure) -> go.Figure: color = 'rgba(136, 78, 160, 0.5)' position = (1, 1) outstreched = self.result fig.add_trace(go.Bar( x=self.data['date'], y=outstreched, marker_color=color, name='outstreched indicator', ), row=position[0], col=position[1]) return fig
def plot(self, fig: go.Figure) -> go.Figure: width = 2 color = 'rgb(46, 134, 193)' slope = self.result fig.add_trace(go.Scatter(x=self.data['date'], y=slope, mode='lines', name='slope', line=dict(color=color, width=width)), row=1, col=1) return fig
def plot(self, fig: go.Figure) -> go.Figure: size = 3 color = 'rgb(46, 134, 193)' renko, renko_dates = self.result fig.add_trace(go.Scatter(x=renko_dates, y=renko, mode='markers', name='renko', marker=dict(color=color, size=size)), row=1, col=1) return fig
def __add_canon_nodes_numbers( fig: go.Figure, canon_nodes_number: int, anon_nodes_number_freq: Dict[int, int]) -> go.Figure: fig.add_trace( go.Scatter(mode='markers', x=[canon_nodes_number], y=[anon_nodes_number_freq.get(canon_nodes_number, 1) / 2], marker=dict(color='White', size=20, line=dict(width=1, color='DarkSlateGrey')), showlegend=False, marker_symbol='x', hoverinfo='skip')) return fig
def plot(self, fig: go.Figure, name: str, color: str = 'rgba(46, 134, 193, 0.5)') -> go.Figure: width = 2 wma = self.result fig.add_trace(go.Scatter(x=self.data['date'], y=wma, mode='lines', name=name, line=dict(color=color, width=width)), row=2, col=1) return fig
def plot(self, fig: go.Figure) -> go.Figure: width = 2 color1 = 'rgba(46, 134, 193, 0.5)' position = (1, 1) obv = self.result fig.add_trace(go.Scatter(x=self.data['date'], y=obv, mode='lines', name='obv', line=dict(color=color1, width=width)), row=position[0], col=position[1]) return fig
def plot_with_color(fig: go.Figure, df: pd.DataFrame, column: str) -> None: for color in df["color"].unique(): fdf = df[df["color"] == color] fig.add_trace( go.Scatter( x=fdf["lambda"] + 1, y=fdf[column], error_y=dict( type="data", symmetric=False, array=fdf["top"], arrayminus=fdf["bottom"], ), name=color, ))
def predict_plot(self): data = [[ int(self.priority_spinBox.value()), int(self.department_spinBox.value()), int(self.product_spinBox.value()), int(self.systems_spinBox.value()) ]] df_tmp = pd.DataFrame( data, columns=['priority', 'department', 'product', 'systems']) data = [[ int(self.priority_spinBox_2.value()), int(self.department_spinBox_2.value()), int(self.product_spinBox_2.value()), int(self.systems_spinBox_2.value()) ]] df_tmp_2 = pd.DataFrame( data, columns=['priority', 'department', 'product', 'systems']) tmp = self.df_stock.loc[self.df_stock['ZK2'] == self.__product] plot = (tmp.resample('D')['Betroffenes System'].count().values) plot = plot[plot != 0] plot_1 = np.append(plot, self.__xgb.predict(df_tmp)) plot_2 = np.append(plot, self.__xgb.predict(df_tmp_2)) x = np.arange(1000) y = x**2 fig = Figure(go.Scatter(y=plot_1, name='1')) fig.add_trace(go.Scatter(y=plot_2, name='2')) fig.add_vrect(x0=(len(plot) - 1), x1=(len(plot)), annotation_text="predict", annotation_position="top left", fillcolor="green", opacity=0.25, line_width=0) # we create html code of the figure html = '<html><body>' html += plotly.offline.plot(fig, output_type='div', include_plotlyjs='cdn') html += '</body></html>' # we create an instance of QWebEngineView and set the html code self.widget.setHtml(html)
def add_centers_to_plot(fig: go.Figure, centers: Union[list, np.ndarray], ys: np.ndarray, color: str = 'white') -> go.Figure: """Adds center to 2D heatmap""" fig.add_trace( p1d.trace(x=centers, data=ys, mode='markers', name='Centers', trace_kwargs=dict(marker=dict( color=color, size=3, symbol='circle', )))) return fig
def add_network_pressure_traces( fig: go.Figure, node_info: Dict[str, Any], smry: pd.DataFrame, pressure_plot_mode: PressurePlotMode, real: int, include_bhp: bool, theme_colors: list, ) -> None: """Adding line traces to the network pressures subplot. Missing summary vectors is currently just ignored, but it is possible to show a warning or even raise an exception. """ color_iterator = itertools.cycle(theme_colors) traces = {} for node_network in node_info["networks"]: df = get_filtered_smry(node_network, node_info["ctrlmode_sumvec"], pressure_plot_mode, real, smry) for nodedict in node_network["nodes"]: if nodedict["type"] == NodeType.WELL_BH and not include_bhp: continue sumvec = nodedict["pressure"] label = nodedict["label"] # It the summary vector is not found, do nothing. if sumvec in df.columns: if label not in traces: traces[label] = { "type": "scatter", "x": [], "y": [], "line": dict(color=next(color_iterator)), "name": label, "showlegend": True, "hovertext": (f"{label}"), "legendgroup": "Nodes", "mode": "lines", } traces[label]["x"].extend(list(df["DATE"])) traces[label]["y"].extend(list(df[sumvec])) for trace in traces.values(): fig.add_trace(trace, row=2, col=1)
def add_states(fig: go.Figure, states: List[qu.Qobj], *, mode="markers") -> None: """Draw many states to the given Bloch sphere Figure.""" vectors = np.array([bloch_vector(state) for state in states]) fig.add_trace( go.Scatter3d(x=vectors[:, 0], y=vectors[:, 1], z=vectors[:, 2], mode=mode, marker=dict(color=vectors[:, 2], coloraxis="coloraxis", size=2), hoverinfo="none", showlegend=False, meta=dict(showscale=False)))
def highlight_map(fig: go.Figure, country: str) -> go.Figure: """Highlight a country on the map""" country_index = [ i for i, c in enumerate(fig.data[0]["locations"]) if c == country ][0] highlighted_country = go.Choropleth( locations=[country], z=[fig.data[0]["z"][country_index]], locationmode="country names", text="Highlight", hoverlabel={"bgcolor": styles.default.background_color}, hovertext=[int(fig.data[0]["hovertext"][country_index])], marker_line_color=styles.highlight.map_outline_color, colorscale=[styles.highlight.color, styles.highlight.color], showscale=False, hovertemplate=map_hover_template) fig.add_trace(highlighted_country) return fig