def ps_compare(*analysis_list): fig = go.Figure() raw_symbols = SymbolValidator().values symbols = [ 'circle', 'square', 'cross', 'star-triangle-up', 'star', 'hexagon' ] symbols = cycle(symbols) for analysis in analysis_list: symbol = next(symbols) colors = cycle(px.colors.qualitative.Plotly) for row in analysis.master_table: color = next(colors) fig.add_scatter( x=row['k'] * row['R500'], y=row['ps'], name=row['NAME'] + ' ' + analysis.name, legendgroup=row['NAME'], line_color=color, line_width=2, line_dash='dot', marker_color=color, marker_symbol=symbol, marker_size=7, opacity=0.8, marker_line_color="black", marker_line_width=2, error_y=dict( type='data', # value of error bar given in data coordinates array=np.diag(row['ps_covariance'])**(1 / 2), visible=True)) fig.add_scatter( x=row['k'] * row['R500'], y=row['ps_noise'], name=row['NAME'] + ' PS_noise ' + analysis.name, legendgroup=row['NAME'], line_color='gray', line_width=2, line_dash='dash', opacity=0.2, error_y=dict( type='data', # value of error bar given in data coordinates array=np.diag(row['ps_noise_covariance'])**(1 / 2), visible=True)) fig.update_xaxes(type="log", title_text=r'$k/k_{500}$') fig.update_yaxes( type="log", title_text=r'$\text{Power Spectrum (2D) } [\text{kpc}^{4}]$', automargin=True) return plot(fig, include_mathjax='cdn', output_type='div')
def make_timeplot(df_measure, df_prediction): """ Build figure showing evolution of number of cases vs. time for all countries. The visibility of traces is set to 0 so that the interactive app will toggle the visibility. Parameters ---------- df_measure: pandas DataFrame DataFrame of measured cases, created by :func:`data_input.get_data`, of wide format. df_prediction: pandas DataFrame DataFrame of predictions, with similar structure as df_measure """ # mode = 'confirmed' mode = 'active' df_measure_confirmed = df_measure[mode] colors = px.colors.qualitative.Dark24 n_colors = len(colors) fig = go.Figure() hovertemplate_measure = '<b>%{meta}</b><br>%{x}<br>%{y:.0f}<extra></extra>' hovertemplate_prediction = '<b>%{meta}<br>prediction</b><br>%{x}<br>%{y:.0f}<extra></extra>' for i, country in enumerate(df_measure_confirmed.columns): fig.add_trace( go.Scatter(x=df_measure_confirmed.index, y=df_measure_confirmed[country], name=country[1], mode='markers+lines', marker_symbol=SymbolValidator().values[i], marker_color=colors[i % n_colors], line_color=colors[i % n_colors], meta=country[1], hovertemplate=hovertemplate_measure, visible=False)) prediction = df_prediction['prediction'] upper_bound = df_prediction['upper_bound'] lower_bound = df_prediction['lower_bound'] for i, country in enumerate(prediction.columns): # Do not plot predictions for a country with less than 50 cases if df_measure_confirmed[country][-1] < 50: continue fig.add_trace( go.Scatter(x=prediction.index, y=prediction[country], name='+' + country[1], mode='lines', line_dash='dash', line_color=colors[i % n_colors], showlegend=False, meta=country[1], hovertemplate=hovertemplate_prediction, visible=False)) fig.add_trace( go.Scatter(x=upper_bound.index, y=upper_bound[country], name='+' + country[1], mode='lines', line_dash='dot', line_color=colors[i % n_colors], showlegend=False, visible=False, hoverinfo='skip', line_width=.8)) fig.add_trace( go.Scatter(x=lower_bound.index, y=lower_bound[country], name='+' + country[1], mode='lines', line_dash='dot', line_color=colors[i % n_colors], showlegend=False, visible=False, hoverinfo='skip', line_width=.8)) last_day = df_measure_confirmed.index.max() day = pd.DateOffset(days=1) fig.update_layout(title='', xaxis=dict(rangeslider_visible=True, range=(last_day - 10 * day, last_day + 4 * day))) fig.update_layout( showlegend=True, updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( args=[{ "visible": [ False, ] * len(df_measure_confirmed.columns) }], label="Reset", method="update", ), dict( args=["yaxis", { 'type': 'log' }], label="log", method="relayout", ), dict( args=["yaxis", { 'type': 'linear' }], label="lin", method="relayout", ), ]), pad={ "r": 10, "t": 0, "b": 0 }, showactive=True, x=0.05, xanchor="left", y=1.05, yanchor="top", font_color='black', ), ], xaxis_tickfont_size=LABEL_FONT_SIZE - 4, yaxis_tickfont_size=LABEL_FONT_SIZE - 4, height=FIRST_LINE_HEIGHT, margin=dict(t=0, b=0.02), # The legend position + font size # See https://plot.ly/python/legend/#style-legend legend=dict(x=.05, y=.8, font_size=LABEL_FONT_SIZE, title="Active cases in"), ) return fig
import csv import plotly.graph_objects as go import pandas as pd from plotly.validators.scatter.marker import SymbolValidator symbols = [] raw_symbols = SymbolValidator().values for i in range(0, len(raw_symbols), 12): symbols.append(raw_symbols[i]) def GetCols(filename, col): df = pd.read_csv(filename, usecols=[col]) list = df.keys() ToneScores = df[list[0]].tolist() return ToneScores def GetCovData(country): if country == "US": Covid_Data = GetCols("res/CovidData/UScovidAVG.csv", 0) elif country == "UK": Covid_Data = GetCols("res/CovidData/UKcovidAVG.csv", 0) return Covid_Data def FormatFig(Covid_Data, fig, tone, country, weeks): if country == "UK": source = "GRD" else:
def main(): global filter1, filter2, dt #snname= input('Please give a Supernovae Name: ') filter1 = input('Please specify the first filter: ') filter2 = input('Please specify the second filter: ') dt = input( ('Please specify a dt value or click ENTER for default dt value: ')) #dist_mod= 32.67857985 #filter1 ='UVM2' #filter2 = 'V' pd.set_option('display.max_rows', 1000) swift = pd.read_csv('NewSwiftSNweblist.csv') #Sets plotly background to dark. plotly_white gives white backgound pio.templates.default = "plotly_dark" #Sets up a 3 rowed subplot fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0) #Runs data_Grapher() and returns 3 plots plot_data = swift.apply( lambda row: data_Grapher(row['SNname'], row['Dist_mod_cor']), axis=1).to_list() #plot_data= data_Grapher(snname, dist_mod) #adds those plots to fig ''' fig.append_trace(plot_data[0], row=1, col=1) fig.append_trace(plot_data[1], row=2, col=1) fig.append_trace(plot_data[2], row=3, col=1) ''' for i in range(len(plot_data)): if plot_data[i][0] == "NULL": continue else: fig.append_trace(plot_data[i][0], row=1, col=1) for i in range(len(plot_data)): if plot_data[i][1] == "NULL": continue else: fig.append_trace(plot_data[i][1], row=2, col=1) for i in range(len(plot_data)): if plot_data[i][2] == "NULL": continue else: fig.append_trace(plot_data[i][2], row=3, col=1) fig.update_layout(title_text=filter1 + '-' + filter2 + ' Color Light Curve', legend_title="Supernovae") #Edit axis orientation fig['layout']['yaxis']['autorange'] = "reversed" fig['layout']['yaxis2']['autorange'] = "reversed" #Edit axis labels fig['layout']['xaxis3']['title'] = 'Days since first detection' fig['layout']['yaxis']['title'] = filter1 + ' Absolute Mag' fig['layout']['yaxis2']['title'] = filter2 + ' Absolute Mag' fig['layout']['yaxis3']['title'] = filter1 + '-' + filter2 #cycles through diffferent line types from this list line_styles_names = [ 'solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot' ] line_styles = cycle(line_styles_names) #pulls out specific symbol types from plotly symbol list then cycle through those symbols symbols = [ x for x in SymbolValidator().values[::-2] if not isinstance(x, int) ] symbols = [i for i in symbols if not i.isdigit()] del symbols[8:12] symbols_names = list(set([i.replace("-thin", "") for i in symbols])) markers = cycle(symbols_names) #once one line and marker type is used on a trace, cycle to next one for d in fig.data: d.line["dash"] = next(line_styles) d.marker.symbol = next(markers) d.marker.size = 8 #Error Button fig.update_layout(updatemenus=[ dict( type="buttons", showactive=False, xanchor="left", yanchor="top", x=0.15, y=1.08, buttons=list([ dict(label="Error Bar", method="update", args=[{ "error_y.visible": False }], args2=[{ "error_y.visible": True }]) ]), ) ]) fig.show()
def make_timeplot(df_measure, df_prediction, countries=None): """ Build figure showing evolution of number of cases vs. time for all countries. The visibility of traces is set to 0 so that the interactive app will toggle the visibility. Parameters ---------- df_measure: pandas DataFrame DataFrame of measured cases, created by :func:`data_input.get_data`, of wide format. df_prediction: pandas DataFrame DataFrame of predictions, with similar structure as df_measure countries: list or None (default) list of countries to use for the figure. If None, all countries are used. """ # active cases mode = 'confirmed' df_measure_confirmed = df_measure[mode] df_measure_confirmed = normalize_by_population_wide(df_measure_confirmed) # Plot per million df_measure_confirmed *= 1e6 colors = px.colors.qualitative.Dark24 n_colors = len(colors) fig = go.Figure() hovertemplate_measure = '<b>%{meta}</b><br>%{x}<br>%{y:.0f} per Million<extra></extra>' hovertemplate_prediction = '<b>%{meta}<br>prediction</b><br>%{x}<br>%{y:.0f} per Million<extra></extra>' for i, country in enumerate(df_measure_confirmed.columns): if countries and country[1] not in countries: continue fig.add_trace(go.Scatter(x=df_measure_confirmed.index, y=df_measure_confirmed[country], name=country[1], mode='markers+lines', marker_symbol = SymbolValidator().values[i], marker_color=colors[i%n_colors], line_color=colors[i%n_colors], meta=country[1], hovertemplate=hovertemplate_measure, visible=True)) # predictions prediction = df_prediction['prediction'] upper_bound = df_prediction['upper_bound'] lower_bound = df_prediction['lower_bound'] prediction = normalize_by_population_wide(prediction) prediction *= 1e6 upper_bound = normalize_by_population_wide(upper_bound) upper_bound *= 1e6 lower_bound = normalize_by_population_wide(lower_bound) lower_bound *= 1e6 for i, country in enumerate(prediction.columns): if countries and country[1] not in countries: continue # Do not plot predictions for a country with less than 50 cases if df_measure_confirmed[country][-1] < 50: continue fig.add_trace(go.Scatter(x=prediction.index, y=prediction[country], name='+' + country[1], mode='lines', line_dash='dash', line_color=colors[i%n_colors], showlegend=False, meta=country[1], hovertemplate=hovertemplate_prediction, visible=True)) fig.add_trace(go.Scatter(x=upper_bound.index, y=upper_bound[country], name='+' + country[1], mode='lines', line_dash='dot', line_color=colors[i%n_colors], showlegend=False, visible=True, hoverinfo='skip', line_width=.8)) fig.add_trace(go.Scatter(x=lower_bound.index, y=lower_bound[country], name='+' + country[1], mode='lines', line_dash='dot', line_color=colors[i%n_colors], showlegend=False, visible=True, hoverinfo='skip', line_width=.8)) # fatalities mode = 'death' df_measure_death = df_measure[mode] df_measure_death = normalize_by_population_wide(df_measure_death) # Plot per million df_measure_death *= 1e6 colors = px.colors.qualitative.Dark24 n_colors = len(colors) hovertemplate_fatalities = '<b>%{meta}<br>fatalities</b><br>%{x}<br>%{y:.0f} per Million<extra></extra>' for i, country in enumerate(df_measure_death.columns): if countries and country[1] not in countries: continue fig.add_trace(go.Scatter(x=df_measure_death.index, y=df_measure_death[country], name=' ' + country[1], mode='markers+lines', marker_symbol = SymbolValidator().values[i], marker_color=colors[i%n_colors], line_color=colors[i%n_colors], meta=country[1], hovertemplate=hovertemplate_fatalities, visible=True)) last_day = df_measure_confirmed.index.max() day = pd.DateOffset(days=1) fig.update_layout(title='', xaxis=dict(rangeslider_visible=True, range=(last_day - 10 * day, last_day + 4 * day))) # # vertical line to separate the last day of measurements from prediction fig.add_shape( # Line Vertical dict( type='line', xref='x', yref='paper', x0=last_day, y0=0.05, x1=last_day, y1=0.95, line=dict( color="gray", dash='dash', width=1 ) )) fatalities_annotation = dict(x=0.1, y=0.95, xref='paper', yref='paper', showarrow=False, font_size=LABEL_FONT_SIZE, text='Fatalities per Million', visible=False, ) confirmed_annotation = dict(x=0.1, y=0.95, xref='paper', yref='paper', showarrow=False, font_size=LABEL_FONT_SIZE, text='Confirmed cases per Million', visible=True, ) drag_handle_annotation = dict(x=1, y=-0.1, xref='paper', yref='paper', showarrow=False, font_size=LABEL_FONT_SIZE - 6, font_color="DarkSlateGray", text="Drag handles below to change time window", align="right") fig.update_layout( showlegend=True, annotations=[fatalities_annotation, confirmed_annotation, drag_handle_annotation], xaxis_tickfont_size=LABEL_FONT_SIZE - 4, yaxis_tickfont_size=LABEL_FONT_SIZE - 4, yaxis_type='linear', height=FIRST_LINE_HEIGHT, margin=dict(t=0, b=0.02), # The legend position + font size # See https://plot.ly/python/legend/#style-legend legend=dict(x=.05, y=.8, font_size=LABEL_FONT_SIZE) ) return fig
def run(self): textboxValue = self.mainwindow.ui.lineEdit.text() if textboxValue != '': stock = pdr.get_data_yahoo(textboxValue, start=datetime.datetime(2006, 10, 1), end=datetime.datetime.now()) short_window = self.mainwindow.ui.spinBox_short.value() self.mainwindow.ui.horizontalSlider_short.setValue(short_window) long_window = self.mainwindow.ui.spinBox_long.value() self.mainwindow.ui.horizontalSlider_long.setValue(long_window) try: signals_company = self.simple_trade_strategy( stock, short_window, long_window) raw_symbols = SymbolValidator().values marker_triangle_up = raw_symbols[raw_symbols.index( 'triangle-up')] marker_triangle_down = raw_symbols[raw_symbols.index( 'triangle-down')] self.fig_strategy = go.Figure() self.fig_strategy.add_trace( go.Scatter( x=stock.index, y=stock['Adj Close'], mode='lines', # line=dict(width=4), name='Adj Close')) self.fig_strategy.add_trace( go.Scatter(x=signals_company.index, y=signals_company['short_mavg'], mode='lines', name='short_mavg')) self.fig_strategy.add_trace( go.Scatter(x=signals_company.index, y=signals_company['long_mavg'], mode='lines', name='long_mavg')) self.fig_strategy.add_trace( go.Scatter(x=signals_company.loc[signals_company.positions == 1.0].index, y=signals_company.short_mavg[ signals_company.positions == 1.0], marker_symbol=marker_triangle_up, mode='markers', marker_size=10, marker_color="yellowgreen", name='buy')) self.fig_strategy.add_trace( go.Scatter(x=signals_company.loc[signals_company.positions == -1.0].index, y=signals_company.short_mavg[ signals_company.positions == -1.0], marker_symbol=marker_triangle_down, mode='markers', marker_size=10, marker_color="black", name='sell')) self.fig_strategy.update_layout( title=get_company_name(textboxValue) + " simple strategy", # xaxis_title='Время', yaxis_title='Цена, $') except Exception as e: print(e)
def state_plot(df: pd.DataFrame, thresh=15): markers = df.tag.value_counts() tag_value_counts = markers >= thresh show_legends = set(tag_value_counts.index.to_numpy()[tag_value_counts]) df["show_legends"] = df["tag"].map(lambda x: x in show_legends) raw_symbols = SymbolValidator().values colors = px.colors.qualitative.Plotly symbol_dict = {} color_dict = {} color_len = len(colors) for idx, tag in enumerate(markers.index): symbol_idx = idx // color_len color_idx = idx % color_len symbol_dict[tag] = raw_symbols[symbol_idx] color_dict[tag] = colors[color_idx] df["color"] = df.tag.map(color_dict) df["symbol"] = df.tag.map(symbol_dict) fig = go.Figure() sel_tags = sorted(show_legends, key=len) for sel_tag in sel_tags: tmp_df = df.loc[df.tag == sel_tag, :] fig.add_trace( go.Scatter( x=tmp_df["D1"], y=tmp_df["D2"], mode="markers", marker_color=tmp_df["color"], marker_symbol=tmp_df["symbol"], hovertemplate="<b>tag:%{text}</b><br>pred_tag:%{customdata}", text=tmp_df["tag"].to_list(), customdata=tmp_df["pred_tag"].to_list(), showlegend=True, name=sel_tag, ) ) no_legend_df = df.loc[~df["show_legends"], :] fig.add_trace( go.Scatter( x=no_legend_df["D1"], y=no_legend_df["D2"], mode="markers", opacity=0.5, marker_color=no_legend_df["color"], marker_symbol=no_legend_df["symbol"], showlegend=False, hovertemplate="<b>tag:%{text}</b><br>pred_tag:%{customdata}", text=no_legend_df["tag"].to_list(), customdata=no_legend_df["pred_tag"].to_list(), name="", ) ) fig.update_xaxes(showticklabels=False) fig.update_yaxes(showticklabels=False) fig.update_layout( template=TEMPLATE, font_family="Arial", legend=dict( orientation="h", ), width=1280, height=600, ) return fig
def plot_lines_plotly_animated( df, title, show_doubling=True, doubling_days=7, showlegend=False ): doubling_column = f"double_x{doubling_days}" if show_doubling: def double_every_x_days(day, days_doubling): r = 1 * 2 ** (day / days_doubling) return r df["day"] = df.index df[doubling_column] = df["day"].apply( lambda x: double_every_x_days(x, doubling_days) ) del df["day"] # Create traces fig = go.Figure() labels = [c for c in df.columns if c != doubling_column] max_y_range = int(max(df.loc[:, labels].max()) * 1.1) # max_x_range = len(df.index) colors = ( plotly.colors.diverging.Temps + plotly.colors.diverging.Temps ) # 10 colors #['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)'] symbols = [ x for i, x in enumerate(SymbolValidator().values) if i % 2 != 0 ] # all markers gray_color = "rgb(204, 204, 204)" days = df.index animation_speed = 50 mode_size = [8] * len(df.columns) # [8, 8, 12, 8] line_size = [1] * len(df.columns) # [2, 2, 4, 2] for i, col in enumerate(df.columns): # Adding Doubling x7 line if col == doubling_column: fig.add_trace( go.Scatter( x=df.index, y=df[col], mode="lines", marker=dict( color=gray_color, size=mode_size[i] - 2, opacity=0.7, symbol=symbols[i + 2], line=dict(color=colors[i], width=1), ), name=col, line=dict(color=gray_color, width=line_size[i], dash="dot",), connectgaps=True, ) ) # Adding all other lines else: fig.add_trace( go.Scatter( x=df.index, y=df[col], mode="lines+markers", marker=dict( color=colors[i], size=mode_size[i] - 3, opacity=0.7, symbol=symbols[i + 2], line=dict(color=colors[i], width=1), ), name=col, line=dict(color=colors[i], width=line_size[i]), connectgaps=False, ) ) # BUTTONS Changing Y Scale updatemenus = list( [ dict( active=1, buttons=list( [ dict( label="Scale: Log", method="update", args=[ {"visible": [True, True]}, { "title": "Log scale", "yaxis": { "type": "log", "range": [0, np.log10(max_y_range)], "showgrid": False, "zeroline": False, "showline": False, "linecolor": "#1f2630", }, }, ], ), dict( label="Scale: Linear", method="update", args=[ {"visible": [True, True]}, { "title": "Linear scale", "yaxis": { "type": "linear", "range": [0, max_y_range], # 'showticklabels': False, "showgrid": False, "zeroline": False, "showline": False, "linecolor": "#1f2630", }, }, ], ), dict( label="Play", method="animate", args=[ None, { "frame": { "duration": animation_speed, "redraw": False, }, "fromcurrent": True, "transition": { "duration": animation_speed * 0.8, "easing": "quadratic-in-out", }, }, ], ), dict( args=[ [None], { "frame": {"duration": 0, "redraw": False}, "mode": "immediate", "transition": {"duration": 0}, }, ], label="Pause", method="animate", ), ] ), type="buttons", pad={"r": 10, "t": 10}, showactive=True, x=-0.15, xanchor="left", # ['auto', 'left', 'center', 'right'] y=0.35, yanchor="bottom", # ['auto', 'top', 'middle', 'bottom'] ) ] ) # ===== SLIDER AND FRAMES ================================================================== sliders_dict = { "active": 0, "yanchor": "top", "xanchor": "left", "currentvalue": { "font": {"size": 20}, "prefix": "Day:", "visible": True, "xanchor": "right", }, "transition": {"duration": animation_speed, "easing": "cubic-in-out"}, "pad": {"b": 10, "t": 50}, "len": 0.9, "x": 0.1, "y": 0, "steps": [], } # ==== MAKE FRAMES ======================================================================== frames_list = list() for day in df.index: frame = go.Frame(data=[], name=str(day)) data_list = [] for label in labels: dataset_by_day_label = df.loc[min(df.index) : day, label] data_dict = { "x": list(dataset_by_day_label.index), # list(day), "y": list(dataset_by_day_label.values), "mode": "lines+markers", "text": list(label), # "marker": { # "sizemode": "area", # # "sizeref": 200000, # "size": list(dataset_by_day_label.values) # }, # "name": label } data_list.append(data_dict) frame["data"] = data_list frames_list.append(frame) slider_step = { "args": [ [day], { "frame": {"duration": animation_speed, "redraw": False}, "mode": "immediate", "transition": {"duration": animation_speed}, }, ], "label": day, "method": "animate", } sliders_dict["steps"].append(slider_step) fig["frames"] = frames_list # fig_dict["layout"]["sliders"] = [sliders_dict] # ===== END SLIDER AND FRAMES ===== # ===== UPDATE LAYOUT, Axis, Margins, Size, Legend, Background ========================= fig.update_layout( updatemenus=updatemenus, sliders=[sliders_dict], xaxis=dict( showline=True, showgrid=False, showticklabels=True, linecolor=gray_color, linewidth=2, ticks="outside", tickfont=dict( family="Arial", size=12, color="#2cfec1", #'rgb(82, 82, 82)', ), # range=[0,max_x_range], ), yaxis=dict( showgrid=False, zeroline=False, showline=False, showticklabels=True, tickfont=dict(color="#2cfec1"), range=[0, max_y_range], ), autosize=False, margin=dict( autoexpand=True, # l=150, # r=0, # t=110, # b=90, ), showlegend=showlegend, legend_orientation="v", legend=dict(x=1.05, y=0,), paper_bgcolor="#1f2630", # "#F4F4F8", plot_bgcolor="#1f2630", # 'white' font=dict(color="#2cfec1"), width=1200, height=600, ) # ANNOTATIONS annotations = [] # Adding labels for i, col in enumerate(df.columns): if col == doubling_column: # labeling x7 line y = 52 # df.loc[int(max(df.index/2)), 'x7'] x = 40 # int(max(df.index)/2) annotations.append( dict( xref="x", x=x, y=y, xanchor="center", yanchor="middle", text="double every 7 days", font=dict(family="Arial", size=12, color=gray_color,), showarrow=False, ) ) continue # labeling the left_side of the plot # y = df.loc[min(df[col].dropna().index),col] # annotations.append(dict(xref='paper', x=0.07, y=y, # xanchor='right', yanchor='middle', # text=col + ' {}'.format(y), # font=dict(family='Arial', # size=10), # showarrow=False)) # labeling the right_side of the plot x = max(df[col].dropna().index) y = df.loc[max(df[col].dropna().index), col] annotations.append( dict( xref="paper", x=0.95, y=y, xanchor="left", yanchor="middle", text=f"{col}: {int(y)}", font=dict(family="Arial", size=12), showarrow=False, ) ) # Title annotations.append( dict( xref="paper", yref="paper", x=0, y=1, xanchor="left", yanchor="bottom", text=title, font=dict(family="Garamond", size=30, color="#7fafdf"), #'rgb(37,37,37)' showarrow=False, ) ) # Source annotations.append( dict( xref="paper", yref="paper", x=0.5, y=-0.08, xanchor="center", yanchor="top", text="<a href=”https://www.rki.de/”> Data Source: Robert Koch Institute</a><br><i>Charts: Sergey Chekanskiy</i>", font=dict(family="Arial", size=12, color="#7fafdf"), showarrow=False, ) ) fig.update_layout(annotations=annotations) return fig
def iplot_line(wf_list, y, x='TIME', color='auto', range_y='auto', line_shape='spline', rangeslider_visible=False, line_group='DEPTH', resample=None, view_maxmin=True, trend=False, **kwds): """ It uses plotly.express.line. Each data point is represented as a marker point, whose location is given by the x and y columns of self.data. Parameters ---------- wf_list: List(WaterFrame) List of WaterFrame objects. y: str List[str] Y axes, columns of data (max 4 columns). x: str X axes, column or index of data. color: str Name of a column or index of data. Values from this column are used to assign color to marks. If color = 'auto', color = QC column of y. range_y: list [min value, max value] of y axes. If range_y = 'auto', range is generated between the mina nd max values of y axes +- 5%. line_shape: str Line options: 'linear' 'spline', 'vhv', 'hvh', 'vh', 'hv' rangeslider_visible: bool Show a time range slide on the bottom x axes. line_group: str or int or Series or array-like Either a name of a column in wf.data, or a pandas Series or array_like object. Values from this column or array_like are used to group rows of data_frame into lines. resample: str Get the plot with resample data. If resample, color = 'DEPTH and each y is represented with a different simbol view_maxmin: bool Show the max and min values if data is resampled. trend: bool Show a linear regression of the trace. **kwds: keywords plotly express scatter keywords. Returns ------- fig: plotly.graph_objects.Figure """ # Load all simbols raw_symbols = SymbolValidator().values symbols = [] for i in range(1, len(raw_symbols), 8): symbols.append(raw_symbols[i]) list_y = [] if isinstance(y, str): list_y = [y] else: list_y = y # Color configuration # fillcolor_list = [ # 'rgba(0,100,80,0.2)', # 'rgba(0,176,246,0.2)', # 'rgba(231,107,243,0.2)', # 'rgba(240,184,48,0.2)', # 'rgba(245,71,26,0.2)', # 'rgba(227,245,65,0.2)', # 'rgba(0,0,0,0.2)', # 'rgba(94,86,245,0.2)', # 'rgba(157,49,245,0.2)', # 'rgba(255,0,0,0.2)', # 'rgba(0,255,0,0.2)', # 'rgba(0,0,255,0.2)', # 'rgba(0,100,100,0.2)'] # line_color_list = [ # 'rgb(0,100,80)', # 'rgb(0,176,246)', # 'rgb(231,107,243)', # 'rgb(240,184,48)', # 'rgb(245,71,26)', # 'rgb(227,245,65)', # 'rgb(0,0,0)', # 'rgb(94,86,245)', # 'rgb(157,49,245)', # 'rgb(255,0,0)', # 'rgba(0,255,0,0.2)', # 'rgba(0,0,255,0.2)', # 'rgba(0,100,100,0.2)'] fillcolor_list = [ 'rgba(51,0,0,0.2)', 'rgba(102,51,0,0.2)', 'rgba(153,153,0,0.2)', 'rgba(102,204,0,0.2)', 'rgba(0,255,0,0.2)', 'rgba(51,255,153,0.2)', 'rgba(102,255,255,0.2)', 'rgba(153,204,255,0.2)', 'rgba(204,204,255,0.2)', 'rgba(204,153,255,0.2)', 'rgba(255,102,255,0.2)', 'rgba(255,51,153,0.2)', 'rgba(128,128,128,0.2)', 'rgba(204,0,102,0.2)', 'rgba(153,0,153,0.2)', 'rgba(51,0,102,0.2)', 'rgba(0,0,51,0.2)', 'rgba(0,51,102,0.2)', 'rgba(0,153,153,0.2)', 'rgba(0,204,102,0.2)', 'rgba(153,255,51,0.2)', 'rgba(255,255,102,0.2)', 'rgba(255,204,153,0.2)', 'rgba(255,204,204,0.2)', 'rgba(255,0,0,0.2)', 'rgba(255,153,51,0.2)', 'rgba(255,255,102,0.2)', 'rgba(204,255,153,0.2)', 'rgba(204,255,204,0.2)', 'rgba(153,255,204,0.2)', 'rgba(102,255,255,0.2)', 'rgba(51,153,255,0.2)', 'rgba(0,0,255,0.2)', 'rgba(153,0,153,0.2)', 'rgba(102,0,51,0.2)', 'rgba(0,0,0,0.2)', ] line_color_list = [ 'rgb(51,0,0)', 'rgb(102,51,0)', 'rgb(153,153,0)', 'rgb(102,204,0)', 'rgb(0,255,0)', 'rgb(51,255,153)', 'rgb(102,255,255)', 'rgb(153,204,255)', 'rgb(204,204,255)', 'rgb(204,153,255)', 'rgb(255,102,255)', 'rgb(255,51,153)', 'rgb(128,128,128)', 'rgb(204,0,102)', 'rgb(153,0,153)', 'rgb(51,0,102)', 'rgb(0,0,51)', 'rgb(0,51,102)', 'rgb(0,153,153)', 'rgb(0,204,102)', 'rgb(153,255,51)', 'rgb(255,255,102)', 'rgb(255,204,153)', 'rgb(255,204,204)', 'rgb(255,0,0)', 'rgb(255,153,51)', 'rgb(255,255,102)', 'rgb(204,255,153)', 'rgb(204,255,204)', 'rgb(153,255,204)', 'rgb(102,255,255)', 'rgb(51,153,255)', 'rgb(0,0,255)', 'rgb(153,0,153)', 'rgb(102,0,51)', 'rgb(0,0,0)', ] fig = go.Figure() for num_wf, wf in enumerate(wf_list): dash = 'solid' if num_wf == 1: dash = 'dash' elif num_wf == 2: dash = 'dot' elif num_wf > 2: dash = 'dashdot' _df = wf.data.reset_index() for y_num, one_y in enumerate(list_y): # yaxis config yaxis = 0 if y_num == 0: yaxis = 'y' elif y_num == 1: yaxis = 'y2' elif y_num == 2: yaxis = 'y3' elif y_num == 3: yaxis = 'y4' else: raise 'Error, cannot add more than 4 "y" parameters' df = pd.DataFrame() df[one_y] = _df[one_y] df[f'{one_y}_QC'] = _df[f'{one_y}_QC'] df[x] = _df[x] if 'DEPTH' in _df.keys(): df['DEPTH'] = _df['DEPTH'] # Range Y calculation y_min = min(df[one_y].values) y_max = max(df[one_y].values) y_percent = (y_max - y_min) / 100 if range_y == 'auto': range_y = [y_min - 5 * y_percent, y_max + 5 * y_percent] # Dropna df.dropna(inplace=True) if 'DEPTH' in df.keys() and 'TIME' in df.keys(): # Sort by TIME AND DEPTH df.sort_values(['DEPTH', 'TIME'], inplace=True) elif 'TIME' in df.keys(): df.sort_values(['TIME'], inplace=True) if resample: color = 'DEPTH' if color == 'DEPTH': df[color] = df[color].astype('str') elif color == 'auto': color = f'{one_y}_QC' if resample: df_agg = df.groupby( ['DEPTH'] + [pd.Grouper(freq=resample, key='TIME')]).agg( {one_y: ['mean', 'max', 'min']}) df_agg.reset_index(inplace=True) df_agg['mean'] = df_agg[one_y]['mean'] df_agg['max'] = df_agg[one_y]['max'] df_agg['min'] = df_agg[one_y]['min'] for color_comt, (depth, df_depth) in enumerate( df_agg.groupby('DEPTH')): # Create color r_color = random.randint(0, 255) g_color = random.randint(0, 255) b_color = random.randint(0, 255) df_depth.set_index('TIME', inplace=True) df_depth['values_from_start'] = (df_depth.index - df_depth.index[0]).days df_depth.reset_index(inplace=True) x_time = df_depth['TIME'] x_days = df_depth['values_from_start'] x_rev = x_time[::-1] y_mean = df_depth['mean'] y_max = df_depth['max'] y_min = df_depth['min'] y_min = y_min[::-1] if trend: reg = LinearRegression().fit(np.vstack(x_days), y_mean) bestfit = reg.predict(np.vstack(x_days)) fig.add_trace( go.Scatter( x=x_time, y=bestfit, name= f'trend-{wf.metadata["platform_code"]}-{one_y}-{depth}', # line_shape=line_shape, mode='lines+markers', yaxis=yaxis, marker_symbol=symbols[y_num], line=dict(dash=dash))) if view_maxmin: fig.add_trace( go.Scatter( x=pd.concat([x_time, x_rev]), y=pd.concat([y_max, y_min]), fill='toself', # fillcolor=fillcolor_list[selected_color], fillcolor= f'rgba({r_color},{g_color},{b_color},0.2)', line_color='rgba(255,255,255,0)', showlegend=True, name= f'{wf.metadata["platform_code"]}-{one_y}-{depth}-MaxMin', line_shape=line_shape, yaxis=yaxis, line=dict(dash=dash))) fig.add_trace( go.Scatter( x=x_time, y=y_mean, # line_color=line_color_list[selected_color], line_color=f'rgb({r_color},{g_color},{b_color})', name= f'{wf.metadata["platform_code"]}-{one_y}-{depth}', line_shape=line_shape, yaxis=yaxis, marker_symbol=symbols[y_num], line=dict(dash=dash))) fig.update_traces(mode='lines+markers') # Update yaxis fig.update_layout(xaxis=dict(title='Time')) try: if y_num == 0: fig.update_layout(yaxis=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})" )) elif y_num == 1: fig.update_layout(yaxis2=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})", side="right", overlaying="y")) elif y_num == 2: fig.update_layout( xaxis=dict(domain=[0.07, 1], title='Time')) fig.update_layout(yaxis3=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})", overlaying="y", side="left", position=0)) elif y_num == 3: fig.update_layout( xaxis=dict(domain=[0.07, 0.93], title='Time')) fig.update_layout(yaxis4=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})", overlaying="y", side="right", position=1)) except: pass # Add 'Depth' to legend fig.update_layout( legend_title={ 'text': 'Platform Code - Parameter - Depth (m)' }) else: for color_comt, (depth, df_depth) in enumerate(df.groupby('DEPTH')): # Create color r_color = random.randint(0, 255) g_color = random.randint(0, 255) b_color = random.randint(0, 255) df_depth.set_index('TIME', inplace=True) df_depth['values_from_start'] = (df_depth.index - df_depth.index[0]).days df_depth.reset_index(inplace=True) x_time = df_depth['TIME'] x_days = df_depth['values_from_start'] y_plot = df_depth[one_y] if trend: reg = LinearRegression().fit(np.vstack(x_days), y_plot) bestfit = reg.predict(np.vstack(x_days)) fig.add_trace( go.Scatter( x=x_time, y=bestfit, name= f'trend-{wf.metadata["platform_code"]}-{one_y}-{depth}', # line_shape=line_shape, mode='lines+markers', yaxis=yaxis, marker_symbol=symbols[y_num], line=dict(dash=dash))) fig.add_trace( go.Scatter( x=x_time, y=y_plot, line_color=f'rgb({r_color},{g_color},{b_color})', name= f'{wf.metadata["platform_code"]}-{one_y}-{depth}', line_shape=line_shape, yaxis=yaxis, marker_symbol=symbols[y_num], line=dict(dash=dash))) fig.update_traces(mode='lines+markers') # Update yaxis fig.update_layout(xaxis=dict(title='Time')) try: if y_num == 0: fig.update_layout(yaxis=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})" )) elif y_num == 1: fig.update_layout(yaxis2=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})", side="right", overlaying="y")) elif y_num == 2: fig.update_layout( xaxis=dict(domain=[0.07, 1], title='Time')) fig.update_layout(yaxis3=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})", overlaying="y", side="left", position=0)) elif y_num == 3: fig.update_layout( xaxis=dict(domain=[0.07, 0.93], title='Time')) fig.update_layout(yaxis4=dict( title= f"{one_y} - {wf.vocabulary[one_y]['long_name']} ({wf.vocabulary[one_y]['units']})", overlaying="y", side="right", position=1)) except: pass # Add 'Depth' to legend fig.update_layout( legend_title={ 'text': 'Platform Code - Parameter - Depth (m)' }) fig.update_xaxes(rangeslider_visible=rangeslider_visible) fig.update_layout(margin=dict(l=30, r=0, t=30, b=0)) if 'QC' in color: fig.for_each_trace( lambda trace: trace.update( visible='legendonly', mode='markers', marker_color='red') if trace.name == 'Bad data' else (), ) fig.for_each_trace( lambda trace: trace.update(mode='lines+markers', marker_color='blue', line_color='blue') if trace.name == 'Good data' else (), ) return fig
def chart(data, data_rolling, countries, by_million_inh=False, align_curves=False, last_d=15, offset_name='offset_confirmed', type_ppl="confirmed cases", name_fig="", since=False, min_rate=0, log=False, new=""): today = datetime.now().strftime("%Y-%m-%d %H:%M") ### Symbols symbols = [] for i in range(35): symbols.append(SymbolValidator().values[i]) random.shuffle(symbols) ### fig = go.Figure() i = 0 j = 0 x_an = np.array([]) y_an = np.array([]) countries_last_val = [] countries_array = [] for c in countries: if by_million_inh: val = data[c][len(data) - 1] / countries[c]['pop'] else: val = data[c][len(data) - 1] countries_last_val.append(val) countries_array.append(c) ind = np.argsort(countries_last_val) countries_array = np.array(countries_array) countries_array = countries_array[ind][::-1] for c in countries_array: if align_curves: offset = countries[c][offset_name] offset2 = -offset else: offset = 0 if offset == 0: offset2 = None if by_million_inh: pop = countries[c]['pop'] else: pop = 1 date = 'date' offset3 = 0 since_str = "" since_str_leg = "" if since: date = 'date_int' res = list(map(lambda i: i > min_rate, data[c + new].values / pop)) offset2 = 0 if True in res: ind = res.index(True) offset2 = -ind since_str_leg = " [since {} days]".format(len(data) - ind) offset3 = offset2 last_d = 0 offset = 0 since_str = " [since {}]".format(min_rate) #, type_ppl if by_million_inh: since_str = since_str[:-1] + "/1M inh.]" x = data[date][-last_d - offset:offset2] y = data[c + new][-last_d - offset3:] / pop if offset != 0: name_legend = '{} [delayed by {} days]'.format(c, -offset) else: name_legend = '{} {}'.format(c, since_str_leg) txt = ["" for i in range(len(data_rolling[c][-last_d - offset3:]))] txt[-1] = c fig.add_trace( go.Scatter( x=x, y=y, mode='markers', marker_color=colors[countries[c]['color']], legendgroup=c, marker_symbol=countries[c]['color'], marker_size=5, #marker_line_width=2, opacity=1, showlegend=True, name=name_legend)) fig.add_trace( go.Scatter(x=data_rolling[date][-last_d - offset:offset2], y=data_rolling[c + new][-last_d - offset3:] / pop, mode='lines', marker_color=colors[countries[c]['color']], opacity=1, legendgroup=c, showlegend=False, line=dict(width=1.7), name=name_legend)) i += 1 j += 1 if i >= len(colors): i = 0 if j >= 40: j = 0 if log and since and c == "Italy": date_start = data_rolling['date_int'].values[-last_d - offset] x = data_rolling["date_int"][-last_d - offset:offset2] max_values = 15 for (rate, rate_str) in [(2**(1 / 10), "x2 every 10 days"), (2**(1 / 7), "x2 every 7 days"), (2**(1 / 3), "x2 every 3 days"), (2**(1 / 2), "x2 every 2 days"), (2**(1 / 5), "x2 every 5 days")]: y = rate**( data_rolling["date_int"][-last_d - offset:offset2].values - date_start) * min_rate fig.add_trace( go.Scatter( x=x[:max_values + 1], y=y[:max_values + 1], mode='lines+text', marker_color="grey", opacity=1, #text = rate_str, textposition="bottom right", legendgroup="Tendance", showlegend=False, line=dict(width=1, dash='dot'), name="Tendance")) fig.add_trace( go.Scatter(x=[ data_rolling["date_int"] [-last_d - offset:offset2].values[max_values] ], y=[(rate**(data_rolling["date_int"] [-last_d - offset:offset2].values - date_start) * min_rate)[max_values]], mode='text', marker_color="grey", opacity=1, text=rate_str, textposition="bottom right", legendgroup="Tendance", showlegend=False, name="Tendance")) ### END LOOP ### align_str = "" if align_curves: align_str = " [aligned]" million_str = "" million_str_ax = "" if by_million_inh: million_str = " for 1M inhabitants" million_str_ax = "/ nb of inhabitants (million)" delayed = "" if align_curves: delayed = "— delayed for some countries" if since: delayed = "— since {} {} {}".format(min_rate, type_ppl, million_str) fig.update_annotations( dict(xref="x", yref="y", showarrow=True, arrowhead=7)) log_str = "linear" if log: log_str = "log" fig.update_layout( showlegend=True, title={ 'text': "COVID-19 <b>{}{}</b>{}{}".format(type_ppl, million_str, align_str, since_str), 'y': 0.95, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' }, xaxis_title="Day {} {}".format(delayed, ''), yaxis_type=log_str, yaxis_title="Total {} {}".format(type_ppl, million_str), titlefont=dict(size=28), annotations=[ dict( xref='paper', yref='paper', x=0, y=1.05, showarrow=False, text= 'Last update: {} ; Last data: {} ; Data: CSSE ; Author: @guillaumerozier' .format(today, str(data['date'].values[-1])[:10])) ]) #fig.update_xaxes(nticks = last_d) print("> graph built") if upload: py.plot(fig, filename=name_fig, auto_open=False) print("> graph uploaded") if show: fig.show() print("> graph showed") if export: path_log = "" if log: path_log = "log_yaxis/" fig.write_image(PATH + "images/charts/{}{}.jpeg".format(path_log, name_fig), scale=2, width=1100, height=700) #fig.write_image("images/charts_sd/{}{}.png".format(path_log, name_fig), scale=0.5) plotly.offline.plot( fig, filename=PATH + 'images/html_exports/{}{}.html'.format(path_log, name_fig), auto_open=False) print("> graph exported\n") return fig
def plot_tid_for_datasets(fileList, t_id): """ Takes in a list of oeb files and plots wbo vs torsion barrier, combining all the datasets and plotting by each tid in the combined dataset Parameters ---------- fileList: list of strings each string is a oeb file name Eg. ['rowley.oeb'] or ['rowley.oeb', 'phenyl.oeb'] t_id: str torsion id, eg., 't43' """ import base64 import ntpath from io import BytesIO import pandas as pd import plotly.express as px import plotly.graph_objects as go from plotly.validators.scatter.marker import SymbolValidator from rdkit import Chem from rdkit.Chem.Draw import MolsToGridImage df = pd.DataFrame(columns = ['tid', 'tb', 'wbo', 'cmiles', 'TDindices', 'filename']) fig = go.Figure({'layout' : go.Layout(height=900, width=1000, xaxis={'title': 'Wiberg Bond Order'}, yaxis={'title': 'Torsion barrier (kJ/mol)'}, #paper_bgcolor='white', plot_bgcolor='rgba(0,0,0,0)', margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'orientation': 'h', 'y': -0.2}, legend_font=dict(family='Arial', color='black', size=15), hovermode=False, dragmode='select')}) fig.update_xaxes(title_font=dict(size=26, family='Arial', color='black'), ticks="outside", tickwidth=2, tickcolor='black', ticklen=10, tickfont=dict(family='Arial', color='black', size=20), showgrid=False, gridwidth=1, gridcolor='black', mirror=True, linewidth=2, linecolor='black', showline=True) fig.update_yaxes(title_font=dict(size=26, family='Arial', color='black'), ticks="outside", tickwidth=2, tickcolor='black', ticklen=10, tickfont=dict(family='Arial', color='black', size=20), showgrid=False, gridwidth=1, gridcolor='black', mirror=True, linewidth=2, linecolor='black', showline=True) colors = fragmenter.chemi._KELLYS_COLORS colors = colors * 2 raw_symbols = SymbolValidator().values symbols = [] for i in range(0,len(raw_symbols),8): symbols.append(raw_symbols[i]) count = 0 fname = [] for fileName in fileList: molList = [] fname = fileName molList = oeb2oemol(fname) for m in molList: tid = m.GetData("IDMatch") fname = ntpath.basename(fileName) df = df.append({'tid': tid, 'tb': m.GetData("TB"), 'wbo' : m.GetData("WBO"), 'cmiles' : m.GetData("cmiles"), 'TDindices' : m.GetData("TDindices"), 'filename' : fname}, ignore_index = True) x = df[(df.filename == fname) & (df.tid == t_id)].wbo y = df.loc[x.index].tb fig.add_scatter(x=x, y=y, mode="markers", name=fname, marker_color=colors[count], marker_symbol=count, marker_size=13) count += 1 x = df[df.tid == t_id].wbo y = df.loc[x.index].tb slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) print("tid: ", t_id, "r_value: ", r_value, "slope: ", slope, "intercept: ", intercept) fig.add_traces(go.Scatter( x=np.unique(x), y=np.poly1d([slope, intercept])(np.unique(x)), showlegend=False, mode ='lines')) slope_text = 'slope: '+str('%.2f' % slope) r_value = 'r_val: '+str('%.2f' % r_value) fig_text = slope_text + ', '+ r_value fig.add_annotation(text=fig_text, font = {'family': "Arial", 'size': 22, 'color': 'black'}, xref="paper", yref="paper", x=1, y=1, showarrow=False) fig.update_layout( title={"text": t_id, "x": 0.5, "xanchor": "center", "yanchor": "top"} ) fig.show() return fig
def plot_lines_stacked_plotly( df, column, _colors=[ "#81b2ca", "#dea986", "#87e7fc", "#d3aedf", "#93b48f", "#a7afe6", "#f7fffa", "#bba5b5" ], title=False, showlegend=True, ): seterr(divide="ignore") # Create traces fig = go.Figure() _labels = df["land"].unique() # max_x_range = len(df.index) # _max_y_range = df.loc[df.date == df.date.max(), column].sum() * 1.15 _max_y_range = df.loc[:, [column]].groupby( by=['date']).sum()[column].max() * 1.1 if df.loc[:, column].min() > 0: _min_y_range = (df.loc[(df[column] > 0), column].min() / 2) else: _min_y_range = df.loc[:, column].min() * 1.1 _symbols = [ x for i, x in enumerate(SymbolValidator().values) if i % 2 != 0 ] # all markers _gray_color = "rgb(204, 204, 204)" _mode_size = [8] * len(_labels) # [8, 8, 12, 8] _line_size = [1] * len(_labels) # [2, 2, 4, 2] for i, l in enumerate(_labels): fig.add_trace( go.Scatter( x=df.loc[df.land == l].index, y=df.loc[df.land == l, column], mode="lines", name=l, line=dict(color=_colors[i], width=_line_size[i]), connectgaps=False, stackgroup='one' # define stack group )) # endpoints min_index, max_index = ( df.loc[df.land == l].index.min(), df.loc[df.land == l].index.max(), ) fig.add_trace( go.Scatter( x=[min_index, max_index], y=[ df.loc[(df.index == min_index) & (df.land == l)], df.loc[(df.index == max_index) & (df.land == l)], ], mode="markers", name=l, marker=dict( color=_colors[i], size=_mode_size[i] + 2, ), showlegend=False, )) # BUTTONS Changing Y Scale updatemenus = list([ dict( active=1, direction="left", buttons=list([ dict( label="Log", method="update", args=[ { "visible": [True, True] }, { # 'title': 'Log scale', "yaxis": { "type": "log", "range": [ log10(_min_y_range), log10(_max_y_range), ], "showgrid": False, "zeroline": False, "showline": False, "linecolor": "#1f2630", } }, ], ), dict( label="Linear", method="update", args=[ { "visible": [True, True] }, { # 'title': 'Linear scale', "yaxis": { "type": "linear", "range": [_min_y_range, _max_y_range], # 'showticklabels': False, "showgrid": False, "zeroline": False, "showline": False, "linecolor": "#1f2630", } }, ], ), ]), type="buttons", pad={ "r": 10, "t": 10 }, showactive=True, x=0.10, xanchor="left", # ['auto', 'left', 'center', 'right'] y=1, yanchor="top", # ['auto', 'top', 'middle', 'bottom'] ) ]) # UPDATE LAYOUT, Axis, Margins, Size, Legend, Background fig.update_layout( updatemenus=updatemenus, dragmode="select", clickmode="event+select", xaxis=dict( showline=True, showgrid=False, showticklabels=True, linecolor=_gray_color, linewidth=2, ticks="outside", tickfont=dict( family="Arial", size=12, color="#2cfec1", # 'rgb(82, 82, 82)', ), # range=[0,max_x_range], ), yaxis=dict( showgrid=False, zeroline=False, showline=False, showticklabels=True, tickfont=dict(color="#2cfec1"), range=[_min_y_range, _max_y_range], ), margin=dict( autoexpand=True, l=10, r=100, t=10, b=100, ), showlegend=showlegend, legend_orientation="h", legend=dict( x=0, y=1.3, ), paper_bgcolor="#1f2630", # "#F4F4F8", plot_bgcolor="#1f2630", # 'white' font=dict(color="#2cfec1"), autosize=True, # width=800, # height=500, ) # ANNOTATIONS annotations = [] # Title if title: annotations.append( dict( xref="paper", yref="paper", x=0, y=1, xanchor="left", yanchor="bottom", text=title, font=dict( family="Garamond", size=30, color="#7fafdf" # 'rgb(37,37,37)' ), showarrow=False, )) fig.update_layout(annotations=annotations) return fig
def plot_lines_plotly(df, title, show_doubling=True, doubling_days=7, showlegend=False): import plotly.graph_objects as go from plotly.validators.scatter.marker import SymbolValidator doubling_column = f"double_x{doubling_days}" if show_doubling: def double_every_x_days(day, days_doubling): d = np.ceil(day / days_doubling) r = 1 * 2 ** (day / days_doubling) return r df["day"] = df.index df[doubling_column] = df["day"].apply( lambda x: double_every_x_days(x, doubling_days) ) del df["day"] # Create traces fig = go.Figure() labels = [c for c in df.columns if c != doubling_column] max_y_range = int(max(df.loc[:, labels].max()) * 1.1) # max_x_range = len(df.index) colors = ( plotly.COLORS.sequential.Viridis + plotly.COLORS.sequential.Viridis ) # 10 colors #['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)'] symbols = [ x for i, x in enumerate(SymbolValidator().values) if i % 2 != 0 ] # all markers # print(len(labels)) # print(len(colors)) gray_color = "rgb(204, 204, 204)" mode_size = [8] * len(df.columns) # [8, 8, 12, 8] line_size = [1] * len(df.columns) # [2, 2, 4, 2] for i, col in enumerate(df.columns): # Adding Doubling x7 line if col == doubling_column: fig.add_trace( go.Scatter( x=df.index, y=df[col], mode="lines", marker=dict( color=gray_color, size=mode_size[i] - 2, opacity=0.7, symbol=symbols[i + 2], line=dict(color=colors[i], width=1), ), name=col, line=dict(color=gray_color, width=line_size[i], dash="dot",), connectgaps=True, ) ) # Adding all other lines else: fig.add_trace( go.Scatter( x=df.index, y=df[col], mode="lines+markers", marker=dict( color=colors[i], size=mode_size[i] - 3, opacity=0.7, symbol=symbols[i + 2], line=dict(color=colors[i], width=1), ), name=col, line=dict(color=colors[i], width=line_size[i]), connectgaps=False, ) ) # endpoints fig.add_trace( go.Scatter( x=[min(df[col].dropna().index), max(df[col].dropna().index)], y=[ df.loc[min(df[col].dropna().index), col], df.loc[max(df[col].dropna().index), col], ], mode="markers", name=col, marker=dict(color=colors[i], size=mode_size[i] + 2,), showlegend=False, ) ) # BUTTONS Changing Y Scale updatemenus = list( [ dict( active=1, buttons=list( [ dict( label="Log Scale", method="update", args=[ {"visible": [True, True]}, { "title": "Log scale", "yaxis": { "type": "log", "range": [0, np.log10(max_y_range)], }, }, ], ), dict( label="Linear Scale", method="update", args=[ {"visible": [True, False]}, { "title": "Linear scale", "yaxis": { "type": "linear", "range": [0, max_y_range], "showticklabels": False, }, }, ], ), dict(label="Play", method="animate", args=[None]), ] ), ) ] ) # UPDATE LAYOUT, Axis, Margins, Size, Legend, Background fig.update_layout( updatemenus=updatemenus, xaxis=dict( showline=True, showgrid=False, showticklabels=True, linecolor=gray_color, linewidth=2, ticks="outside", tickfont=dict(family="Arial", size=12, color="rgb(82, 82, 82)",), ), yaxis=dict( showgrid=False, zeroline=False, showline=False, showticklabels=True, range=[0, max_y_range], ), autosize=False, margin=dict(autoexpand=True, l=150, r=30, t=110, b=90,), showlegend=showlegend, legend_orientation="v", legend=dict(x=1.1, y=0,), plot_bgcolor="white", width=1200, height=900, ) # ANNOTATIONS annotations = [] # Adding labels for i, col in enumerate(df.columns): if col == doubling_column: # labeling x7 line y = 52 # df.loc[int(max(df.index/2)), 'x7'] x = 40 # int(max(df.index)/2) annotations.append( dict( xref="x", x=x, y=y, xanchor="center", yanchor="middle", text="double every 7 days", font=dict(family="Arial", size=12, color=gray_color,), showarrow=False, ) ) continue # labeling the left_side of the plot # y = df.loc[min(df[col].dropna().index),col] # annotations.append(dict(xref='paper', x=0.07, y=y, # xanchor='right', yanchor='middle', # text=col + ' {}'.format(y), # font=dict(family='Arial', # size=10), # showarrow=False)) # labeling the right_side of the plot x = max(df[col].dropna().index) y = df.loc[max(df[col].dropna().index), col] annotations.append( dict( xref="paper", x=0.95, y=y, xanchor="left", yanchor="middle", text=f"{col}: {int(y)}", font=dict(family="Arial", size=12), showarrow=False, ) ) # Title annotations.append( dict( xref="paper", yref="paper", x=0, y=1, xanchor="left", yanchor="bottom", text=title, font=dict(family="Garamond", size=30, color="rgb(37,37,37)"), showarrow=False, ) ) # Source annotations.append( dict( xref="paper", yref="paper", x=0.5, y=-0.1, xanchor="center", yanchor="top", text="Source: Robert Koch Institute & " + "Storytelling with data", font=dict(family="Arial", size=12, color="rgb(150,150,150)"), showarrow=False, ) ) fig.update_layout(annotations=annotations) fig.show()
def plot_lines_plotly( df, column, _colors=colors.diverging.Temps * 3, title=False, show_doubling=True, doubling_days=7, showlegend=False, ): seterr(divide="ignore") _doubling_column = f"double_x{doubling_days}" if show_doubling: def double_every_x_days(day, days_doubling, start_value=1): r = start_value * 2 ** (day / days_doubling) return r start_value = df.loc[ (df[column] > 0) & (df.index == df.index.min()), column ].median() if start_value < 1: start_value = 1 # prepare empty dataframe to fill in date_range = pd.date_range(df.index.min(), df.index.max()) df_index = pd.DataFrame( columns=["date", "land", column], data={"date": date_range, "land": _doubling_column}, ) # create a column with rank 1,2,3 etc for every 'land' in this case doubling types df_index["rn"] = df_index.groupby("land")["date"].rank( method="first", ascending=True ) df_index[column] = df_index["rn"].apply( lambda x: double_every_x_days(x, doubling_days, start_value) ) df_index["date"] = df_index["date"].astype("datetime64[ns]") df_index.set_index("date", inplace=True, drop=False) df_index.sort_index(inplace=True, ascending=True) del df_index["rn"] df = df.append(df_index, ignore_index=False, verify_integrity=False, sort=True) # Create traces fig = go.Figure() _labels = df["land"].unique() # max_x_range = len(df.index) _max_y_range = df.loc[df.land != _doubling_column, column].max() * 1.1 if df.loc[:, column].min() > 0: _min_y_range = ( df.loc[(df.land != _doubling_column) & (df[column] > 0), column].min() / 2 ) else: _min_y_range = df.loc[(df.land != _doubling_column), column].min() * 1.1 _symbols = [ x for i, x in enumerate(SymbolValidator().values) if i % 2 != 0 ] # all markers _gray_color = "rgb(204, 204, 204)" _mode_size = [8] * len(_labels) # [8, 8, 12, 8] _line_size = [1] * len(_labels) # [2, 2, 4, 2] for i, l in enumerate(_labels): # Adding Doubling x7 line if l == _doubling_column: fig.add_trace( go.Scatter( x=df.loc[df.land == l].index, y=df.loc[df.land == l, column], mode="lines", marker=dict( color=_gray_color, size=_mode_size[i] - 2, opacity=0.7, symbol=_symbols[i + 2], line=dict(color=_colors[i], width=1), ), name=l, line=dict(color=_gray_color, width=_line_size[i], dash="dot",), connectgaps=True, ) ) # Adding all other lines else: fig.add_trace( go.Scatter( x=df.loc[df.land == l].index, y=df.loc[df.land == l, column], mode="lines+markers", marker=dict( color=_colors[i], size=_mode_size[i] - 1, opacity=0.7, symbol=_symbols[i + 2], line=dict(color=_colors[i], width=1), ), name=l, line=dict(color=_colors[i], width=_line_size[i]), connectgaps=False, ) ) # endpoints min_index, max_index = ( df.loc[df.land == l].index.min(), df.loc[df.land == l].index.max(), ) fig.add_trace( go.Scatter( x=[min_index, max_index], y=[ df.loc[(df.index == min_index) & (df.land == l)], df.loc[(df.index == max_index) & (df.land == l)], ], mode="markers", name=l, marker=dict(color=_colors[i], size=_mode_size[i] + 2,), showlegend=False, ) ) if "confirmed_peak_date" in df.columns: # Mark when the peak is reached peak_index = df.loc[ (df.land == l) & (df["confirmed_peak_date"] == 1), column ].index.tolist() fig.add_trace( go.Scatter( x=peak_index, y=df.loc[ (df.index.isin(peak_index)) & (df.land == l), column ].tolist(), # y=[df.loc[(df.index == peak_index) & (df.land == l), column]], mode="markers", name=f"Peak {l}", marker=dict( color="#008000", size=15, opacity=1, symbol="triangle-down", line=dict( # color=_colors[i], width=1 ), ), showlegend=False, ) ) # Mark when the new peak is starting (new wave is approaching) peak_index = df.loc[ (df.land == l) & (df["confirmed_peak_date"] == -1), column ].index.tolist() fig.add_trace( go.Scatter( x=peak_index, y=df.loc[ (df.index.isin(peak_index)) & (df.land == l), column ].tolist(), mode="markers", name=f"New Wave {l}", marker=dict( color="#FF0000", size=15, opacity=1, symbol="triangle-up", line=dict( # color=_colors[i], width=1 ), ), showlegend=False, ) ) # # Mark when we predict the perk to be reached # peak_index = df.loc[(df.land == l) & (df['peak_log_trend'] < 0), column].index.tolist() # fig.add_trace(go.Scatter( # x=peak_index, # # y=[df.loc[df['peak_log_trend'] < 0, column].max().round(2)], # y=df.loc[(df.index.isin(peak_index)) & (df.land == l), column].tolist(), # mode='lines+markers', # name=f"fc: {l}", # marker=dict( # color=_colors[i], # size=20, # opacity=1, # symbol='triangle-up', # line=dict( # color=_colors[i], # width=1 # )), # showlegend=False, # )) # BUTTONS Changing Y Scale updatemenus = list( [ dict( active=1, direction="left", buttons=list( [ dict( label="Log", method="update", args=[ {"visible": [True, True]}, { # 'title': 'Log scale', "yaxis": { "type": "log", "range": [ log10(_min_y_range), log10(_max_y_range), ], "showgrid": False, "zeroline": False, "showline": False, "linecolor": "#1f2630", } }, ], ), dict( label="Linear", method="update", args=[ {"visible": [True, True]}, { # 'title': 'Linear scale', "yaxis": { "type": "linear", "range": [_min_y_range, _max_y_range], # 'showticklabels': False, "showgrid": False, "zeroline": False, "showline": False, "linecolor": "#1f2630", } }, ], ), ] ), type="buttons", pad={"r": 10, "t": 10}, showactive=True, x=0.10, xanchor="left", # ['auto', 'left', 'center', 'right'] y=1, yanchor="top", # ['auto', 'top', 'middle', 'bottom'] ) ] ) # UPDATE LAYOUT, Axis, Margins, Size, Legend, Background fig.update_layout( updatemenus=updatemenus, dragmode="select", clickmode="event+select", xaxis=dict( showline=True, showgrid=False, showticklabels=True, linecolor=_gray_color, linewidth=2, ticks="outside", tickfont=dict( family="Arial", size=12, color="#2cfec1", # 'rgb(82, 82, 82)', ), # range=[0,max_x_range], ), yaxis=dict( showgrid=False, zeroline=False, showline=False, showticklabels=True, tickfont=dict(color="#2cfec1"), range=[_min_y_range, _max_y_range], ), margin=dict(autoexpand=True, l=10, r=100, t=10, b=100,), showlegend=showlegend, legend_orientation="v", legend=dict(x=1.05, y=0,), paper_bgcolor="#1f2630", # "#F4F4F8", plot_bgcolor="#1f2630", # 'white' font=dict(color="#2cfec1"), autosize=True, # width=800, # height=500, ) # ANNOTATIONS annotations = [] # Adding labels for i, l in enumerate(_labels): min_index, max_index = ( df.loc[df.land == l].index.min(), df.loc[df.land == l].index.max(), ) if l == _doubling_column: # labeling x7 line x = min_index + (max_index - min_index) / 2 try: x = str(x.date()) except: pass y = df.loc[(df.land == l) & (df.index == x), column].values[0] annotations.append( dict( xref="x", x=x, y=y, xanchor="center", yanchor="middle", text="double every 7 days", font=dict(family="Arial", size=12, color=_gray_color,), showarrow=False, ) ) else: # labeling the right_side of the plot y = df.loc[(df.land == l) & (df.index == max_index), column].values[0] annotations.append( dict( xref="paper", x=0.95, y=y, xanchor="left", yanchor="middle", text=l, # f"{col}: {int(y)}", font=dict(family="Arial", size=12, color=_colors[i]), showarrow=False, ) ) # ======================================= ANNOTATE DATA OUTLIERS ======================== annotation_style_outliers = dict( xref="x", yref="y", showarrow=True, arrowhead=2, arrowsize=1.2, arrowwidth=1.2, arrowcolor=_gray_color, # bordercolor=_gray_color, # borderwidth=2, # borderpad=4, # bgcolor=_gray_color, # "#ff7f0e" opacity=0.5, ax=0, ay=-40, font=dict(family="Garamond", size=12, color=_gray_color), ) if l == "Hamburg": try: annotation = annotation_style_outliers annotation["text"] = "HH: Recorded old cases" x = df.loc[ (df.date == "2020-05-12") & (df.land == l), [column] ].index[0] y = df.loc[(df.index == x) & (df.land == l), column].values[0] annotation["x"] = x annotation["y"] = df.loc[ (df.index == x) & (df.land == l), column ].values[0] annotations.append(annotation) except: pass # =================================== END ANNOTATE DATA OUTLIERS ======================== # Title if title: annotations.append( dict( xref="paper", yref="paper", x=0, y=1, xanchor="left", yanchor="bottom", text=title, font=dict( family="Garamond", size=30, color="#7fafdf" #'rgb(37,37,37)' ), showarrow=False, ) ) # Source # annotations.append(dict(xref='paper', yref='paper', x=0.5, y=-0.06, # xanchor='center', yanchor='top', # text="Data Source: <a href='https://www.rki.de/'>Robert Koch Institute</a>" # ", <a href='https://www.apple.com/covid19/mobility'>Apple</a><br>" # "<i>Charts: <a href='https://www.linkedin.com/in/sergeychekanskiy'>Sergey Chekanskiy</a></i>", # font=dict(family='Garamond', # size=12, # color='#7fafdf'), # showarrow=False)) fig.update_layout(annotations=annotations) return fig
def plot_tid_for_ff_from_targets(fileList, t_id, ffname, ener_tag): """ Takes in a list of oeb files and plots wbo vs torsion barrier, combining all the datasets and plotting by each tid in the combined dataset Parameters ---------- fileList: list of strings each string is a oeb file name Eg. ['rowley.oeb'] or ['rowley.oeb', 'phenyl.oeb'] t_id: str torsion id, eg., 't43' """ import base64 import ntpath from io import BytesIO import pandas as pd import plotly.express as px import plotly.graph_objects as go from plotly.validators.scatter.marker import SymbolValidator from rdkit import Chem from rdkit.Chem.Draw import MolsToGridImage df = pd.DataFrame( columns=["tid", "tb", "wbo", "cmiles", "TDindices", "TDid", "filename"] ) fig = go.Figure( { "layout": go.Layout( height=900, width=1000, xaxis={"title": "ELF10 Wiberg Bond Order"}, yaxis={"title": "Torsion barrier (kcal/mol)"}, # paper_bgcolor='white', plot_bgcolor="rgba(0,0,0,0)", margin={"l": 40, "b": 40, "t": 10, "r": 10}, legend={"orientation": "h", "y": -0.2}, legend_font=dict(family="Arial", color="black", size=15), hovermode=False, dragmode="select", ) } ) fig.update_xaxes( title_font=dict(size=26, family="Arial", color="black"), ticks="outside", tickwidth=2, tickcolor="black", ticklen=10, tickfont=dict(family="Arial", color="black", size=20), showgrid=False, gridwidth=1, gridcolor="black", mirror=True, linewidth=2, linecolor="black", showline=True, ) fig.update_yaxes( title_font=dict(size=26, family="Arial", color="black"), ticks="outside", tickwidth=2, tickcolor="black", ticklen=10, tickfont=dict(family="Arial", color="black", size=20), showgrid=False, gridwidth=1, gridcolor="black", mirror=True, linewidth=2, linecolor="black", showline=True, ) colors = KELLYS_COLORS colors = colors * 2 raw_symbols = SymbolValidator().values symbols = [] for i in range(0, len(raw_symbols), 8): symbols.append(raw_symbols[i]) count = 0 fname = [] for fileName in fileList: molList = [] fname = fileName molList = oeb2oemol(fname) for m in molList: tid = m.GetData("IDMatch_" + ffname) fname = ntpath.basename(fileName) df = df.append( { "tid": tid, "tb": m.GetData("TB_" + ffname + "_" + ener_tag), "wbo": m.GetData("WBO"), "cmiles": m.GetData("cmiles"), "TDindices": m.GetData("TDindices"), "TDid": m.GetData("TDid"), "filename": fname, }, ignore_index=True, ) x = df[(df.filename == fname) & (df.tid == t_id)].wbo y = df.loc[x.index].tb fig.add_scatter( x=x, y=y, mode="markers", name=fname, marker_color=colors[count], marker_symbol=count, marker_size=13, ) count += 1 x = df[df.tid == t_id].wbo y = df.loc[x.index].tb z = df.loc[x.index].TDid display(z) # with open("qca_ids_included.txt", "ab") as f: # np.savetxt(f, z.values, fmt='%d') slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) print( "tid: ", t_id, "r_value: ", r_value, "slope: ", slope, "intercept: ", intercept ) fig.add_traces( go.Scatter( x=np.unique(x), y=np.poly1d([slope, intercept])(np.unique(x)), showlegend=False, mode="lines", ) ) slope_text = "slope: " + str("%.2f" % slope) r_value = "r_val: " + str("%.2f" % r_value) fig_text = slope_text + ", " + r_value fig.add_annotation( text=fig_text, font={"family": "Arial", "size": 22, "color": "black"}, xref="paper", yref="paper", x=1, y=1, showarrow=False, ) fig.update_layout( title={"text": t_id, "x": 0.5, "xanchor": "center", "yanchor": "top"} ) fig.show() return fig
}), dcc.Dropdown(id='x-dropdown', options=[{ 'label': i, 'value': i } for i in color_dat], value='UVW2-UVW1') return label1, label2 #List of line styles to cycle through in update_Graph. line_styles_names = [ 'solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot' ] #List of marker styles to cycle through in update_Graph. symbols = [x for x in SymbolValidator().values[::-2] if not isinstance(x, int)] symbols = [i for i in symbols if not i.isdigit()] del symbols[8:12] symbols_names = list(set([i.replace("-thin", "") for i in symbols])) @app.callback(Output("SNe-scatter", "figure"), [ Input("y-dropdown", "value"), Input('x-dropdown', 'value'), State('dt', 'value'), State('SNe-type', 'value') ]) def update_Graph(y, x, dt, SNtype): #Cycles through line styles line_style = cycle(line_styles_names)