Ejemplo n.º 1
0
    dcc.Graph(
        figure=go.Figure(
            data=[
                go.Scatter(
                    x=df.Date,
                    y=df.Close,
                    mode='lines',
                    fill='tozeroy',
                    name='Amazon'
                )
            ],
            layout=go.Layout(
                yaxis_type='log',
                height=500,
                title_text='Wykres ceny',
                showlegend=True

            )

        )
    ),

    dcc.Graph(
        figure=go.Figure(
            data=[go.Bar(
                x=df.Date,
                y=df.Volume,
                name='Wolumen'

            )
Ejemplo n.º 2
0
def get_journey(data, pi, title, idx_in_batch = 0):
	"""Plots journey of agent
	Args:
		data: dataset of graphs
		pi: (batch, decode_step) # tour
		idx_in_batch: index of graph in data to be plotted
	"""

	# Remove extra zeros
	pi_ = get_clean_path(pi[idx_in_batch].numpy())

	# Unpack variables
	depo_coord = data[0][idx_in_batch].numpy()
	points_coords = data[1][idx_in_batch].numpy()
	demands = data[2][idx_in_batch].numpy()
	node_labels = ['(' + str(x[0]) + ', ' + x[1] + ')' for x in enumerate(demands.round(2).astype(str))]

	# Concatenate depot and points
	full_coords = np.concatenate((depo_coord.reshape(1, 2), points_coords))

	# Get list with agent loops in path
	list_of_paths, cur_path = [], []
	for idx, node in enumerate(pi_):

		cur_path.append(node)

		if idx != 0 and node == 0:
			if cur_path[0] != 0:
				cur_path.insert(0, 0)
			list_of_paths.append(cur_path)
			cur_path = []

	list_of_path_traces = []
	for path_counter, path in enumerate(list_of_paths):
		coords = full_coords[[int(x) for x in path]]

		# Calculate length of each agent loop
		lengths = np.sqrt(np.sum(np.diff(coords, axis = 0) ** 2, axis = 1))
		total_length = np.sum(lengths)

		list_of_path_traces.append(go.Scatter(x = coords[:, 0],
											  y = coords[:, 1],
											  mode = "markers+lines",
											  name = f"path_{path_counter}, length = {total_length:.2f}",
											  opacity = 1.0))

	trace_points = go.Scatter(x = points_coords[:, 0],
							  y = points_coords[:, 1],
							  mode = 'markers+text',
							  name = 'destinations',
							  text = node_labels,
							  textposition = 'top center',
							  marker = dict(size = 7),
							  opacity = 1.0
							  )

	trace_depo = go.Scatter(x = [depo_coord[0]],
							y = [depo_coord[1]],
							text = ['1.0'], textposition = 'bottom center',
							mode = 'markers+text',
							marker = dict(size = 15),
							name = 'depot'
							)

	layout = go.Layout(title = '<b>Example: {}</b>'.format(title),
					   xaxis = dict(title = 'X coordinate'),
					   yaxis = dict(title = 'Y coordinate'),
					   showlegend = True,
					   width = 1000,
					   height = 1000,
					   template = "plotly_white"
					   )

	data = [trace_points, trace_depo] + list_of_path_traces
	print('Current path: ', pi_)
	fig = go.Figure(data = data, layout = layout)
	fig.show()
Ejemplo n.º 3
0
    def word_cloud(self):
        wc = WordCloud(
            stopwords=stopwords(),
            max_words=2500,
            color_func=lambda word, font_size, position, orientation, random_state, font_path: random_color(),
        )
        wc.generate_from_frequencies(
            pd.Series(
                np.concatenate(self.df[CLEANED_TEXT].values)
            ).value_counts()
        )

        word_list = []
        freq_list = []
        fontsize_list = []
        position_list = []
        orientation_list = []
        color_list = []
        for (word, freq), fontsize, position, orientation, color in wc.layout_:
            word_list.append(word)
            freq_list.append(freq)
            fontsize_list.append(fontsize)
            position_list.append(position)
            orientation_list.append(orientation)
            color_list.append(color)

        # get the positions
        x = []
        y = []
        for i in position_list:
            x.append(i[0])
            y.append(i[1])

        # get the relative occurrence frequencies
        new_freq_list = []
        for i in freq_list:
            new_freq_list.append(i * 100)

        trace = go.Scatter(
            x=x,
            y=y,
            textfont=dict(size=new_freq_list, color=color_list),
            hoverinfo="text",
            hovertext=[
                "{} {:.2f}%".format(w, f * 100)
                for w, f in zip(word_list, freq_list)
            ],
            mode="text",
            text=word_list,
        )

        layout = go.Layout(
            xaxis=self.hide_axis_dict,
            yaxis=self.hide_axis_dict,
            title="Word Cloud ☁️",
            titlefont_size=self.title_size,
            title_x=0.5,
        )

        fig = go.Figure(data=[trace], layout=layout)

        return fig
Ejemplo n.º 4
0
def main(args):
    # mst_draw(1,'pearson')

    # Create figure
    fig = go.Figure(layout=go.Layout(
        # xaxis=dict(range=[0, 5], autorange=False),
        # yaxis=dict(range=[0, 5], autorange=False),
        title="MST for XXX daya"
        # layout=go.Layout(
        #       xaxis=dict(range=[0, 5], autorange=False),
        #       yaxis=dict(range=[0, 5], autorange=False)
        #       )
    ))

    hasSetNodes = False
    for numb in np.arange(1, 6):
        arr = loadMst(numb)
        G = nx.DiGraph()
        G = addNodesToG(G, arr)
        G = addEdgesToG(G, arr)

        if not hasSetNodes:
            pos = nx.spring_layout(G, scale=2)
            edge_trace = posToEdgeTrace(G, pos)
            node_trace = posToNodeTrace(G, pos)
            hasSetNodes = True
        else:
            edge_trace = posToEdgeTrace(G, pos)

        fig.add_trace(edge_trace)
        fig.add_trace(node_trace)

    # Make 10th trace visible

    # Create and add slider
    steps = []
    for i in range(int(len(fig.data) / 2)):
        step = dict(
            method="restyle",
            args=["visible", [False] * len(fig.data)],
        )
        step["args"][1][i * 2] = True  # Toggle i'th trace to "visible"
        step["args"][1][i * 2 + 1] = True
        steps.append(step)

    # only step 0 is visible
    for x in range(len(fig.data)):
        fig.data[x].visible = False
    fig.data[0].visible = True
    fig.data[1].visible = True

    sliders = [
        dict(active=10,
             currentvalue={"prefix": "Time line: "},
             pad={"t": 50},
             steps=steps)
    ]

    fig.update_layout(
        # updatemenus = [
        #     {
        #         "buttons": [
        #             {
        #                 "args": [step["args"],{"frame": {"duration": 500, "redraw": False},
        #                         "fromcurrent": True, "transition": {"duration": 300,
        #                                                             "easing": "quadratic-in-out"}}],
        #                 "label": "&#9654;", # play symbol
        #                 "method": "animate",
        #             },
        #             # {
        #             #     "args": [None],
        #             #     "label": "&#9724;", # pause symbol
        #             #     "method": "animate",
        #             # },
        #         ],
        #         "direction": "up",
        #         "type": "buttons",
        #     }
        #  ],
        sliders=sliders)

    # fig.update_layout(
    #     updatemenus=[dict(
    #         type="buttons",
    #         buttons=[dict(label="Play",
    #                       method="animate",
    #                       args=[None])])]
    # )

    fig.show()
Ejemplo n.º 5
0
def points(
    R: np.ndarray, sample: Optional[list] = None, plot_size: int = 500, point_size: float = 30
):  # pragma: no cover
    """Creates a plot of two-dimensional points given their input coordinates. Sampled
    points can be optionally highlighted among all points.

    **Example usage:**

    >>> R = np.random.normal(0, 1, (50, 2))
    >>> sample = [1] * 10 + [0] * 40  # select first ten points
    >>> points(R, sample).show()

    .. image:: ../../_static/normal_pp.png
       :width: 40%
       :align: center
       :target: javascript:void(0);

    Args:
        R (np.array): Coordinate matrix. Rows of this array are the coordinates of the points.
        sample (list[int]): optional subset of sampled points to be highlighted
        plot_size (int): size of the plot in pixels, rendered in a square layout
        point_size (int): size of the points, proportional to its radius

    Returns:
         Figure: figure of points with optionally highlighted sample
    """
    try:
        import plotly.graph_objects as go
    except ImportError:
        raise ImportError(plotly_error)

    layout = go.Layout(
        showlegend=False,
        hovermode="closest",
        xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        margin=dict(b=0, l=0, r=0, t=25),
        height=plot_size,
        width=plot_size,
        plot_bgcolor="white",
    )

    p = go.Scatter(
        x=R[:, 0],
        y=R[:, 1],
        mode="markers",
        hoverinfo="text",
        marker=dict(
            color=VERY_LIGHT_GREY, size=point_size, line=dict(color="black", width=point_size / 20)
        ),
    )

    p.text = [str(i) for i in range(len(R))]

    if sample:
        s_x = []
        s_y = []
        sampled_points = [i for i in range(len(sample)) if sample[i] > 0]
        for i in sampled_points:
            s_x.append(R[i, 0])
            s_y.append(R[i, 1])

        samp = go.Scatter(
            x=s_x,
            y=s_y,
            mode="markers",
            hoverinfo="text",
            marker=dict(
                color=RED, size=point_size, line=dict(color="black", width=point_size / 20)
            ),
        )

        samp.text = [str(i) for i in sampled_points]

        f = go.Figure(data=[p, samp], layout=layout)

    else:
        f = go.Figure(data=[p], layout=layout)

    return f
Ejemplo n.º 6
0
def plotly_time_helper(df,
                       mode=None,
                       color=None,
                       marker=None,
                       selector=None,
                       opacity=None,
                       index_str='sig_idx',
                       y_name='iq',
                       x_name=None,
                       minx=None,
                       maxx=None,
                       miny=None,
                       maxy=None,
                       titlesize=12,
                       labelsize=10,
                       legendsize=10,
                       title=None,
                       subplot_title=None,
                       xlabel=None,
                       ylabel=None,
                       xprec=None,
                       yprec=None,
                       plt_size=(8., 6.),
                       stem_plot=False,
                       pickle_fig=False):

    STANDOFF = 10
    column_names = df.columns.to_list()
    sig_indices = np.unique(df[index_str])
    num_sigs = len(sig_indices)

    showlegend = True if num_sigs > 1 else False

    # sig_title = r'$\sf{{{}\}}$'.format(y_name)
    real_str = r'$\Large{{\sf{{{}\ Real}}}}$'.format(
        y_name) if subplot_title is None else subplot_title[0]
    #sig_title + ' ' + REAL_STR
    try:
        imag_str = r'$\Large{{\sf{{{}\ Imag}}}}$'.format(
            y_name) if subplot_title is None else subplot_title[1]
    except:
        imag_str = r'$\Large{{\sf{{{}\ Imag}}}}$'.format(y_name)

    xlabel = SAMP_STR if xlabel is None else xlabel
    ylabel = TAMP_STR if ylabel is None else ylabel

    marker = [dict(size=12, line=None)
              ] * num_sigs if marker is None else marker

    selector = [] * num_sigs if selector is None else selector
    opacity = [1.0] * num_sigs if opacity is None else opacity
    mode = ['lines'] * num_sigs if mode is None else mode
    if stem_plot:
        mode = ['markers'] * num_sigs

    comp_sig = False
    ymins = []
    ymaxs = []
    for idx in sig_indices:
        signal = df[df[index_str] == idx][y_name].to_numpy()
        comp_sig = True if np.iscomplexobj(signal) else comp_sig
        if comp_sig:
            ymins.append(np.min(np.abs(signal)))
            ymaxs.append(np.max(np.abs(signal)))
        else:
            ymins.append(np.min(signal))
            ymaxs.append(np.max(signal))

    miny = np.min(ymins) - .1 * np.min(ymins) if miny is None else miny
    maxy = 1.1 * np.max(ymaxs) if maxy is None else maxy

    # if time dataframe was passed in.

    if comp_sig:
        fig = make_subplots(rows=1,
                            cols=2,
                            specs=[[{}, {}]],
                            subplot_titles=(real_str, imag_str),
                            vertical_spacing=VSPACE,
                            horizontal_spacing=.05,
                            shared_xaxes='rows')
    else:
        fig = make_subplots(rows=1,
                            cols=1,
                            subplot_titles=(real_str, ),
                            vertical_spacing=VSPACE,
                            specs=[[{}]])

    shapes = []
    for ii, (idx, group) in enumerate(df.groupby(index_str)):
        r_idx = ii % len(PALETTE)
        c_idx = (ii + num_sigs) % len(PALETTE)
        x_series = group.index.to_series(
        ) if x_name is None else group[x_name].apply(np.real)
        fig.add_trace(go.Scattergl(x=x_series,
                                   y=group[y_name].apply(np.real),
                                   name='Real {}'.format(idx),
                                   marker_color=PALETTE[r_idx],
                                   marker=marker[ii],
                                   opacity=opacity[ii],
                                   mode=mode[ii],
                                   showlegend=showlegend),
                      row=1,
                      col=1,
                      secondary_y=False)

        if stem_plot:
            shapes.extend([
                dict(type='line',
                     xref='x1',
                     yref='y1',
                     x0=i,
                     y0=0,
                     x1=i,
                     y1=offset_signal(np.real(group[y_name][i]), .001),
                     opacity=opacity[ii],
                     line=dict(color=PALETTE[r_idx], width=2))
                for i in range(len(group[y_name]))
            ])

        # shapes = []
        if comp_sig:
            x_series = group.index.to_series(
            ) if x_name is None else group[x_name].apply(np.real)
            fig.add_trace(go.Scattergl(x=x_series,
                                       y=group[y_name].apply(np.imag),
                                       name='Imag {}'.format(idx),
                                       marker_color=PALETTE[c_idx],
                                       marker=marker[ii],
                                       opacity=opacity[ii],
                                       mode=mode[ii],
                                       showlegend=showlegend),
                          row=1,
                          col=2,
                          secondary_y=False)

            if stem_plot:
                shapes.extend([
                    dict(type='line',
                         xref='x2',
                         yref='y2',
                         x0=i,
                         y0=0,
                         x1=i,
                         y1=offset_signal(np.imag(group[y_name][i]), .001),
                         line=dict(color=PALETTE[c_idx], width=2))
                    for i in range(len(group[y_name]))
                ])

    fig.update_xaxes(tickangle=45,
                     title_text=xlabel,
                     title_font={"size": labelsize},
                     title_standoff=STANDOFF,
                     range=(minx, maxx),
                     row=1,
                     col=1)

    fig.update_yaxes(tickangle=0,
                     title_text=ylabel,
                     title_font={"size": labelsize},
                     title_standoff=STANDOFF,
                     range=(miny, maxy),
                     row=1,
                     col=1)

    if comp_sig:
        fig.update_xaxes(tickangle=45,
                         title_text=xlabel,
                         title_font={"size": labelsize},
                         title_standoff=STANDOFF,
                         range=(minx, maxx),
                         row=1,
                         col=2)

        fig.update_yaxes(tickangle=0,
                         title_text=ylabel,
                         title_font={"size": labelsize},
                         title_standoff=STANDOFF,
                         range=(miny, maxy),
                         row=1,
                         col=2)

    for ann in fig['layout']['annotations']:
        ann['font'] = dict(size=titlesize)  #,color='#ff0000')
        ann['y'] = ann['y'] + .03
        # ann['bargap'] = .95

    fig.update_layout(go.Layout(shapes=shapes, title=title))
    fig.layout.title.font.size = titlesize
    fig.layout.hovermode = 'x'
    return fig
Ejemplo n.º 7
0
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"

from bq_helper import BigQueryHelper
client = BigQueryHelper('bigquery-public-data', 'usa-names')

import plotly.graph_objects as go
from plotly.offline import plot

query = "select name, number from bigquery-public-data.usa_names.usa_1910_current limit 150"

df = client.query_to_pandas(query)

bar = go.Bar(x=df['name'], y=df['number'])

layout = go.Layout(title='Names',
                   xaxis=dict(title='name'),
                   yaxis=dict(title='number'))

fig = go.Figure(data=[bar], layout=layout)

plot(fig)
Ejemplo n.º 8
0
    def graph_residual_error_per_species(self, specie: str) -> go.Figure:
        """
        Graphs the residual errors for each compound that contains specie after applying computed corrections.

        Args:
            specie: the specie/group that residual errors are being plotted for

        Raises:
            ValueError: the specie is not a valid specie that this class fits corrections for
        """

        if specie not in self.species:
            raise ValueError("not a valid specie")

        if len(self.corrections) == 0:
            raise RuntimeError(
                "Please call compute_corrections or compute_from_files to calculate corrections first"
            )

        abs_errors = [
            abs(i)
            for i in self.diffs - np.dot(self.coeff_mat, self.corrections)
        ]
        labels_species = self.names.copy()
        diffs_cpy = self.diffs.copy()
        num = len(labels_species)

        if specie in ("oxide", "peroxide", "superoxide", "S"):
            if specie == "oxide":
                compounds = self.oxides
            elif specie == "peroxide":
                compounds = self.peroxides
            elif specie == "superoxides":
                compounds = self.superoxides
            else:
                compounds = self.sulfides
            for i in range(num):
                if labels_species[num - i - 1] not in compounds:
                    del labels_species[num - i - 1]
                    del abs_errors[num - i - 1]
                    del diffs_cpy[num - i - 1]
        else:
            for i in range(num):
                if not Composition(labels_species[num - i - 1])[specie]:
                    del labels_species[num - i - 1]
                    del abs_errors[num - i - 1]
                    del diffs_cpy[num - i - 1]
        abs_errors, labels_species = (
            list(t) for t in zip(*sorted(zip(abs_errors, labels_species)))
        )  # sort by error

        num = len(abs_errors)
        fig = go.Figure(
            data=go.Scatter(
                x=np.linspace(1, num, num),
                y=abs_errors,
                mode="markers",
                text=labels_species,
            ),
            layout=go.Layout(
                title=go.layout.Title(text="Residual Errors for " + specie),
                yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(
                    text="Residual Error (eV/atom)")),
            ),
        )

        print("Residual Error:")
        print("Median = " + str(np.median(np.array(abs_errors))))
        print("Mean = " + str(np.mean(np.array(abs_errors))))
        print("Std Dev = " + str(np.std(np.array(abs_errors))))
        print("Original Error:")
        print("Median = " + str(abs(np.median(np.array(diffs_cpy)))))
        print("Mean = " + str(abs(np.mean(np.array(diffs_cpy)))))
        print("Std Dev = " + str(np.std(np.array(diffs_cpy))))

        return fig
Ejemplo n.º 9
0
 def get_data(self):
     for week in self.weeks:
         week_tms = {}
         df = pd.read_csv(f'Week_{week}/Regulation.csv')
         df_f = pd.read_csv(f'Week_{week}/Final.csv')
         df_h = pd.read_csv(f'Week_{week}/Halftime.csv')
         df_q = pd.read_csv(f'Week_{week}/Quarter.csv')
         with open(f'Week_{week}/Categories.csv') as cats_file:
             read_data = cats_file.read()
         cats = [x.strip() for x in str(read_data).split(',')]
         week_teams = df.Team.unique().tolist()
         for team in week_teams:
             team_color = self.colors.loc[self.colors.Team == team].Color.values[0].split(',')
             color = f'hsla({team_color[0]}, {team_color[1]}, {str(int(team_color[2])-5*(week-1))},1)'
             tm = Trivia_Team(team, df.loc[df.Team == team],
              df_f.loc[df_f.Team == team],
              df_h.loc[df_h.Team == team],
              df_q.loc[df_q.Team == team],
              cats, week, color)
             self.b_1.append(tm.total_q1)
             self.b_3.append(tm.total_q3)
             self.b_2.append(tm.total_h)
             self.f.append(tm.total_f)
             self.q_1.append(tm.q_1_total)
             self.q_2.append(tm.q_2_total)
             self.q_3.append(tm.q_3_total)
             self.q_4.append(tm.q_4_total)
             if not team in self.team_weeks.keys():
                 self.team_weeks[team] = [[week,tm]]
             else:
                 self.team_weeks[team].append([week,tm])
             week_tms[team] = tm
         max_score = max([week_tms[t].final_score for t in week_teams])
         for team in week_teams:
             week_tms[team].Season_Points = week_tms[team].final_score/max_score*100
         self.overall_weeks[week] = Overall(list(week_tms.values()))
     for team in self.teams:
         games = [x[1] for x in self.team_weeks[team]]
         self.team_season[team] = Season_Team(games)
     self.season_overall = Season_Total(list(self.overall_weeks.values()))
     cats_df = pd.DataFrame(self.season_overall.cats_score, index = ['Answered_Correctly', 'Answered', 'Points_Earned', 'Points_Wagered']).T
     cats_df['Answered_Percent'] = cats_df['Answered_Correctly']/cats_df['Answered']
     cats_df['Points_Percent'] = cats_df['Points_Earned']/cats_df['Points_Wagered']
     self.cats_df = cats_df
     self.season_standings = {t:self.team_season[t].Season_Points for t in self.team_season.keys()}
     season_df = pd.DataFrame(self.season_standings)
     season_df.index = [f'Week_{i+1}' for i in range(10)]
     season_df = season_df.T
     season_df['Total'] = season_df.apply(lambda x: sum(sorted(x, reverse=True)[:5]), axis = 1)
     season_df.sort_values('Total', inplace=True, ascending=False)
     self.season_df = season_df
     for team in self.teams:
         a = self.team_season[team].cats_df.merge(self.cats_df, left_index=True, right_index=True, suffixes=['_Team', '_Total'])
         a.sort_index(inplace=True, ascending = False)
         data = []
         butter_color_template = self.colors.loc[self.colors.Team == team].Color.values[0].split(',')
         butter_color = f'hsl({butter_color_template[0]},{butter_color_template[1]},{butter_color_template[2]})'
         a['team_text'] = a.apply(lambda x: f'Correct: {int(x.Answered_Correctly_Team)}/{int(x.Answered_Team)} <br>Points: {x.Points_Earned_Team}/{x.Points_Wagered_Team}', axis =1)
         a['total_text'] = a.apply(lambda x: f'Correct: {int(x.Answered_Correctly_Total)}/{int(x.Answered_Total)} <br>Points: {x.Points_Earned_Total}/{x.Points_Wagered_Total}', axis =1)
         self.team_season[team].tmp = a.Answered_Percent_Team
         data.append(go.Bar(name = team, y=[i for i in range(len(a.Answered_Percent_Team))],x=a.Answered_Percent_Team, orientation = 'h', marker_color = butter_color, hovertext = a.team_text, hoverinfo = 'text', text = [f'{100*x:.0f}%' for x in a.Answered_Percent_Team], textposition = 'auto'))
         data.append(go.Bar(name = 'Total', y=[i for i in range(len(a.Answered_Percent_Team))],x=a.Answered_Percent_Total, orientation = 'h', xaxis = 'x2', yaxis = 'y2', marker_color = 'darkgrey',hovertext = a.total_text, hoverinfo = 'text', text = [f'{100*x:.0f}%' for x in a.Answered_Percent_Total], textposition = 'auto'))
         data.append(go.Scatter(x = [1 for i in range(len(a.Points_Percent_Team))], y = [i for i in range(len(a.Points_Percent_Team))], orientation = 'h', mode = 'text', text = list(a.index),xaxis = 'x3', yaxis = 'y3', hoverinfo = None, showlegend=False))
         fig = go.Figure(data = data, layout = go.Layout())
         numb_cats = len(a.index)
         fig.update_layout(
             xaxis=dict(
                 domain=[0, 0.45],
                 range = [1.02,0],
             ),
             yaxis=dict(
                 range = [-0.15*numb_cats,1.15*numb_cats],
                 visible = False
             ),
             xaxis2=dict(
                 domain = [0.55, 1],
                 range = [0,1.02],
             ),
             xaxis3=dict(
                 domain = [0.45, 0.55],
                 visible = False
             ),
             yaxis2 = dict(range = [-0.15*numb_cats,1.15*+numb_cats],
                           visible = False),
             yaxis3 = dict(range = [-0.15*numb_cats, 1.15*numb_cats],
                           visible = False)
         )
         self.team_season[team].Butterfly = fig
Ejemplo n.º 10
0
    def global_map(self, data):

        ## Dict with name and 3code
        count_d = dict()

        for count in pycountry.countries:
            count_d[count.alpha_2] = count.alpha_3

        ## Map country to 3code
        data['geoCode'] = data['geoCode'].map(count_d)

        layout = go.Layout(
            geo=dict(bgcolor='rgba(0,0,0,0.8)',
                     subunitcolor='white',
                     showlakes=False),
            font={
                "size": 9,
                "color": "Black"
            },
            titlefont={
                "size": 15,
                "color": "Black"
            },
            margin={
                "r": 0,
                "t": 40,
                "l": 0,
                "b": 0
            },
            paper_bgcolor='white',
            plot_bgcolor='white',
        )

        fig = go.Figure(data=go.Choropleth(locations=data['geoCode'],
                                           z=data[data.columns[2]],
                                           text=data['geoName'],
                                           colorscale='Blues',
                                           autocolorscale=False,
                                           reversescale=False,
                                           marker_line_color='darkgray',
                                           marker_line_width=0.5,
                                           zmax=100,
                                           zmin=0),
                        layout=layout)

        try:
            fig2 = go.Figure(data=go.Choropleth(locations=data['geoCode'],
                                                z=data[data.columns[3]],
                                                text=data['geoName'],
                                                colorscale='Blues',
                                                autocolorscale=False,
                                                reversescale=False,
                                                marker_line_color='darkgray',
                                                marker_line_width=0.5,
                                                zmax=100,
                                                zmin=0),
                             layout=layout)
            fig.add_trace(fig2.data[0])
        except:
            pass
        try:
            fig3 = go.Figure(data=go.Choropleth(locations=data['geoCode'],
                                                z=data[data.columns[4]],
                                                text=data['geoName'],
                                                colorscale='Blues',
                                                autocolorscale=False,
                                                reversescale=False,
                                                marker_line_color='darkgray',
                                                marker_line_width=0.5,
                                                zmax=100,
                                                zmin=0),
                             layout=layout)
            fig.add_trace(fig3.data[0])
        except:
            pass
        try:
            fig4 = go.Figure(data=go.Choropleth(locations=data['geoCode'],
                                                z=data[data.columns[5]],
                                                text=data['geoName'],
                                                colorscale='Blues',
                                                autocolorscale=False,
                                                reversescale=False,
                                                marker_line_color='darkgray',
                                                marker_line_width=0.5,
                                                zmax=100,
                                                zmin=0),
                             layout=layout)
            fig.add_trace(fig4.data[0])
        except:
            pass
        try:
            fig5 = go.Figure(data=go.Choropleth(locations=data['geoCode'],
                                                z=data[data.columns[6]],
                                                text=data['geoName'],
                                                colorscale='Blues',
                                                autocolorscale=False,
                                                reversescale=False,
                                                marker_line_color='darkgray',
                                                marker_line_width=0.5,
                                                zmax=100,
                                                zmin=0),
                             layout=layout)
            fig.add_trace(fig5.data[0])
        except:
            pass

        fig.update_layout(title_text='Interest by Country',
                          width=950,
                          height=725,
                          margin=dict(l=50, r=50, b=50, t=50, pad=1),
                          template="plotly_white",
                          geo=dict(showframe=False,
                                   showcoastlines=False,
                                   projection_type='miller'))

        if len(data.columns[2:7]) == 1:
            fig.show()
        elif len(data.columns[2:7]) == 2:
            fig.update_layout(updatemenus=[
                dict(
                    type="buttons",
                    direction="right",
                    active=0,
                    x=0.60,
                    y=1.05,
                    buttons=list([
                        dict(label=data.columns[2],
                             method='update',
                             args=[{
                                 'visible': [True, False]
                             }]),
                        dict(label=data.columns[3],
                             method='update',
                             args=[{
                                 'visible': [False, True]
                             }]),
                    ]),
                    # fonts and border
                    bgcolor='white',
                    bordercolor='lightgrey',
                    font=dict(size=10))
            ])
            fig.show()
        elif len(data.columns[2:7]) == 3:
            fig.update_layout(updatemenus=[
                dict(
                    type="buttons",
                    direction="right",
                    active=0,
                    x=0.60,
                    y=1.05,
                    buttons=list([
                        dict(label=data.columns[2],
                             method='update',
                             args=[{
                                 'visible': [True, False, False]
                             }]),
                        dict(label=data.columns[3],
                             method='update',
                             args=[{
                                 'visible': [False, True, False]
                             }]),
                        dict(label=data.columns[4],
                             method='update',
                             args=[{
                                 'visible': [False, False, True]
                             }]),
                    ]),
                    # fonts and border
                    bgcolor='white',
                    bordercolor='lightgrey',
                    font=dict(size=10))
            ])
            fig.show()
        elif len(data.columns[2:7]) == 4:
            fig.update_layout(updatemenus=[
                dict(
                    type="buttons",
                    direction="right",
                    active=0,
                    x=0.60,
                    y=1.05,
                    buttons=list([
                        dict(label=data.columns[2],
                             method='restyle',
                             args=[{
                                 'visible': [True, False, False, False]
                             }]),
                        dict(label=data.columns[3],
                             method='update',
                             args=[{
                                 'visible': [False, True, False, False]
                             }]),
                        dict(label=data.columns[4],
                             method='update',
                             args=[{
                                 'visible': [False, False, True, False]
                             }]),
                        dict(label=data.columns[5],
                             method='update',
                             args=[{
                                 'visible': [False, False, False, True]
                             }]),
                    ]),
                    # fonts and border
                    bgcolor='white',
                    bordercolor='lightgrey',
                    font=dict(size=10))
            ])
            fig.show()
        elif len(data.columns[2:7]) == 5:
            fig.update_layout(updatemenus=[
                dict(
                    type="buttons",
                    direction="right",
                    active=0,
                    x=1.00,
                    y=1.05,
                    buttons=list([
                        dict(label=data.columns[2],
                             method='update',
                             args=[{
                                 'visible': [True, False, False, False, False]
                             }]),
                        dict(label=data.columns[3],
                             method='update',
                             args=[{
                                 'visible': [False, True, False, False, False]
                             }]),
                        dict(label=data.columns[4],
                             method='update',
                             args=[{
                                 'visible': [False, False, True, False, False]
                             }]),
                        dict(label=data.columns[5],
                             method='update',
                             args=[{
                                 'visible': [False, False, False, True, False]
                             }]),
                        dict(label=data.columns[6],
                             method='update',
                             args=[{
                                 'visible': [False, False, False, False, True]
                             }]),
                        # fonts and border
                    ]),
                    # fonts and border
                    bgcolor='white',
                    bordercolor='lightgrey',
                    font=dict(size=10))
            ])
            fig.show()
Ejemplo n.º 11
0
import plotly.offline as pyo

df = pd.read_csv('../dataset/2018WinterOlympics.csv')

trace1 = go.Bar(
    x=df['NOC'],  # NOC stands for National Olympic Committee
    y=df['Gold'],
    name='Gold',
    marker=dict(color='#FFD700')  # set the marker color to gold
)
trace2 = go.Bar(
    x=df['NOC'],
    y=df['Silver'],
    name='Silver',
    marker=dict(color='#9EA0A1')  # set the marker color to silver
)
trace3 = go.Bar(
    x=df['NOC'],
    y=df['Bronze'],
    name='Bronze',
    marker=dict(color='#CD7F32')  # set the marker color to bronze
)
data = [trace1, trace2, trace3]

layout = go.Layout(
    title='2018 Winter Olympic Medals by Country',
    barmode='stack'
)
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig)
Ejemplo n.º 12
0
def home_tab2_ebs_radio_callback(cust_name):
    project_fired_hours_cols = ["date"] + [
        col for col in data.fired_hours if cust_name in col
    ]
    project_fired_hours = data.fired_hours[project_fired_hours_cols]
    project_fired_hours['sum'] = project_fired_hours.iloc[:, 1:].sum(axis=1)
    project_fired_hours['cum_sum'] = project_fired_hours['sum'].cumsum()
    project_fired_hours['count'] = range(1,
                                         len(project_fired_hours['sum']) + 1)
    project_fired_hours['mov_avg'] = project_fired_hours[
        'cum_sum'] / project_fired_hours['count']

    moving_average = pd.merge(data.activity_log,
                              project_fired_hours,
                              on='date',
                              how='right')
    trip_event = moving_average[moving_average["outage_type"] == "Trip"]

    fig = {
        'data': [
            go.Scatter(
                x=trip_event["date"],
                y=trip_event["mov_avg"],
                # mode='lines + markers',
                mode='lines',
                # name=f'{cust}',
                # line={'color': next(color1)},
                # marker={'size': 8,
                #         'opacity': 0.5},
                # text=df['BH_Customer_MTBT_pct'],
                # hovertemplate="%{text}%",
            )
        ],
        'layout':
        go.Layout(
            yaxis={
                'title': 'Hours',
                'fixedrange': True,
                'visible': True,
                'linecolor': 'black',
                'rangemode': 'tozero',
                # 'range': [0, y_max * 1.8],
                "tickformat": "s"
            },
            legend=legend_style1,
            font=dict(family=font_family, size=12, color="black"),
            margin={
                'r': 10,
                't': 30,
                'b': 40,
                'l': 50
            },
            xaxis=dict(
                # range=[moving_average["date"].min(), moving_average["date"].max()],
                visible=True,
                linecolor="black",
                # rangeselector=dict(
                #     buttons=list([
                #         dict(count=3,
                #              label="3m",
                #              step="month",
                #              stepmode="backward"),
                #         dict(count=6,
                #              label="6m",
                #              step="month",
                #              stepmode="backward"),
                #         dict(count=1,
                #              label="YTD",
                #              step="year",
                #              stepmode="todate"),
                #         dict(count=1,
                #              label="1y",
                #              step="year",
                #              stepmode="backward"),
                #         dict(step="all")
                #     ])
                # ),
                # type="date"
            ))
    }

    return fig
Ejemplo n.º 13
0
def get_top_off_gr_data(project_events, event_type, next_click, prev_click):

    top_offender_df = project_events[project_events["outage_type"] ==
                                     event_type]
    if top_offender_df.empty:
        return lyt.dummy_fig()
    else:
        # y_max = top_offender_df['total'].max()
        annotations = [
            dict(
                x=0.5,
                y=-0.35,
                showarrow=False,
                text="EBS (System/Group/Component)",
                xref="paper",
                yref="paper",
                font={
                    'size': 14,
                    'family': font_family
                },
            ),
        ]
        ind = get_group(len(top_offender_df.index),
                        (int(next_click) - int(prev_click)), 7)
        top_offender_df_mod = top_offender_df[ind[0]:ind[-1] + 1]
        top_offender_df_mod_validated = top_offender_df_mod[
            top_offender_df_mod["analysis_status"] == "VALIDATED"]
        top_offender_df_mod_tbd = top_offender_df_mod[
            top_offender_df_mod["analysis_status"] == "TBD"]
        top_offender_df_mod_ongoing = top_offender_df_mod[
            top_offender_df_mod["analysis_status"] == "ONGOING"]
        data = [
            go.Bar(
                x=top_offender_df_mod_tbd['label'],
                y=top_offender_df_mod_tbd['status_count'],
                name='To be started',
                marker={'color': to_be_started_col},
                width=0.25,
            ),
            go.Bar(
                x=top_offender_df_mod_ongoing['label'],
                y=top_offender_df_mod_ongoing['status_count'],
                name='Ongoing',
                marker={'color': ongoing_col},
                width=0.25,
            ),
            go.Bar(
                x=top_offender_df_mod_validated['label'],
                y=top_offender_df_mod_validated['status_count'],
                name='Implemented/Validated',
                marker={'color': implemented_col},
                width=0.25,
            )
        ]

        layout = go.Layout(
            yaxis={
                'title': {
                    'text': f'Number of {event_type}',
                    'font': {
                        'size': 14,
                        'family': font_family
                    },
                },
                'fixedrange': True,
                'visible': True,
                'linecolor': 'black',
                # 'range': [0, y_max * 1.2],
                'tickfont': {
                    'size': 12,
                    'family': font_family
                },
                'tickformat': ',d'
            },
            legend=legend_style2,
            annotations=annotations,
            barmode='stack',
            font=dict(family=font_family, size=12, color="black"),
            margin={
                'r': 50,
                't': 40,
                'l': 50
            },
            xaxis={
                'visible': True,
                'linecolor': 'black',
                'tickfont': {
                    'color': 'black',
                    'family': font_family,
                    'size': 12
                }
            },
        )

        fig = {
            'data': data,
            'layout': layout,
        }
        return fig
Ejemplo n.º 14
0
def home_tab2_ebs_radio_callback(responsible_ebs_sel, ebs_system_sel,
                                 ebs_group_sel, ebs_component_sel):

    responsible_ebs_sel = responsible_ebs_sel.strip()
    ebs_system_sel = ebs_system_sel.strip()
    ebs_group_sel = ebs_group_sel.strip()
    ebs_component_sel = ebs_component_sel.strip()

    mask = (events['responsible_ebs'] == responsible_ebs_sel) & (
        events['responsible_system']
        == ebs_system_sel) & (events['responsible_group'] == ebs_group_sel) & (
            events['responsible_component'] == ebs_component_sel)

    df_master_ebs_selcted = events[mask]

    event_count = df_master_ebs_selcted.groupby('projectid').count()
    event_type = df_master_ebs_selcted.groupby('outage_type')
    event_dict = {
        grp: df.groupby('projectid').count()
        for grp, df in event_type
    }
    data = [
        go.Bar(
            x=df.index,
            y=df['outage_type'],
            opacity=0.5,
            name=grp,
        ) for grp, df in event_dict.items()
    ]
    x_title = "Project"

    y_max = event_count['outage_type'].max()
    fig = {
        'data':
        data,
        'layout':
        go.Layout(
            yaxis={
                'title': {
                    'text': 'Event count',
                    'font': {
                        'size': 14,
                        'family': font_family
                    },
                },
                'fixedrange': True,
                'visible': True,
                'linecolor': 'black',
                'range': [0, y_max * 1.2],
                'tickfont': {
                    'size': 12,
                    'family': font_family
                },
                'tickformat': ',d'
            },
            legend=legend_style1,
            barmode='stack',
            font=dict(family=font_family, size=10, color="black"),
            margin={
                'r': 50,
                't': 30,
                'b': 50,
                'l': 50
            },
            xaxis={
                'title': {
                    'text': x_title,
                    'font': {
                        'size': 14,
                        'family': font_family
                    },
                },
                'visible': True,
                'linecolor': 'black',
                'tickfont': {
                    'color': 'black',
                    'family': font_family,
                    'size': 12
                }
            },
        )
    }

    return fig
Ejemplo n.º 15
0
def spectrum(energies: list,
             gamma: float = 100.0,
             xmin: float = None,
             xmax: float = None):  # pragma: no cover
    """Plots a vibronic spectrum based on input sampled energies.

    **Example usage:**

    >>> formic = data.Formic()
    >>> e = vibronic.energies(formic, formic.w, formic.wp)
    >>> full_spectrum = plot.spectrum(e, xmin=-1000, xmax=8000)
    >>> full_spectrum.show()

    .. image:: ../../_static/formic_spectrum.png
       :width: 50%
       :align: center
       :target: javascript:void(0);

    Args:
        energies (list[float]): a list of sampled energies
        gamma (float): parameter specifying the width of the Lorentzian function
        xmin (float): minimum limit of the x axis
        xmax (float): maximum limit of the x axis

    Returns:
         Figure: spectrum in the form of a histogram of energies with a Lorentzian-like curve
    """
    if len(energies) < 2:
        raise ValueError("Number of sampled energies must be at least two")
    try:
        import plotly.graph_objects as go
    except ImportError:
        raise ImportError(plotly_error)

    emin = min(energies)
    emax = max(energies)
    if xmin is None:
        xmin = emin - 0.1 * (emax - emin)
    if xmax is None:
        xmax = emax + 0.1 * (emax - emin)
    bins = int(emax - emin) // 5
    bar_width = (xmax - xmin) * 0.005
    line_width = 3.0

    h = np.histogram(energies, bins)
    X = np.linspace(xmin, xmax, int(xmax - xmin))
    L = 0
    for e in energies:
        L += (gamma / 2)**2 / ((X - e)**2 + (gamma / 2)**2)

    text_font = dict(color="black", family="Computer Modern")

    axis_style = dict(
        titlefont_size=30,
        tickfont=text_font,
        tickfont_size=20,
        showline=True,
        linecolor="black",
        mirror=True,
    )

    layout = go.Layout(
        yaxis=dict(title={
            "text": "Counts",
            "font": text_font
        },
                   **axis_style,
                   rangemode="tozero"),
        xaxis=dict(
            title={
                "text": "Energy (cm<sup>-1</sup>)",
                "font": text_font
            },
            **axis_style,
            range=[xmin, xmax],
        ),
        plot_bgcolor="white",
        margin=dict(t=25),
        bargap=0.04,
        showlegend=False,
    )

    bars = go.Bar(x=h[1].tolist(),
                  y=h[0].tolist(),
                  width=bar_width,
                  marker=dict(color=GREY))

    line = go.Scatter(x=X,
                      y=L,
                      mode="lines",
                      line=dict(color=GREEN, width=line_width))

    f = go.Figure([bars, line], layout=layout)

    return f
Ejemplo n.º 16
0
def DRP_min_e2e_deadline():

    # Compute the min e
    Tfmin = 0.1
    r = np.arange(0.1, 1, 0.01)
    y_source = (2 * DRP_CONF_T_NET_MIN + DRP_CONF_DELTA_CONST_F) / r
    y_dest = (Tfmin + DRP_CONF_DELTA_CONST_G) / (1 - r)

    y_max = np.maximum(y_source, y_dest)
    min_e2e_deadline = (Tfmin + 2 * DRP_CONF_T_NET_MIN +
                        DRP_CONF_DELTA_CONST_F + DRP_CONF_DELTA_CONST_G)
    r_opt = (2 * DRP_CONF_T_NET_MIN +
             DRP_CONF_DELTA_CONST_F) / min_e2e_deadline

    # Plot
    fig = go.Figure()
    notes = []
    shapes = []

    # Admissible region
    fig.add_trace(
        go.Scatter(x=np.append(r, max(r)),
                   y=np.append(y_max, max(y_max)),
                   name='Admissible region',
                   mode='none',
                   fill='toself',
                   fillcolor=colors.light_grey))

    fig.add_trace(
        go.Scatter(
            x=r,
            y=y_source,
            name='(4.22) : Source constraint',
            line={
                'color': colors.blue,
                'dash': 'dash'
            },
        ))
    fig.add_trace(
        go.Scatter(x=r,
                   y=y_dest,
                   name='(4.21) : Dest. constraint',
                   line={'color': colors.orange}))

    # Smallest admissible end-to-end deadline
    # annot_text = ("Smallest admissible<br>end-to-end deadline<br><br>%0.2f s"
    #                 %  min_e2e_deadline )
    annot_text = ("Smallest admissible<br>end-to-end deadline<br><br>")
    annot_text += "<br>with r = %0.2f" % r_opt
    min_dead_annot = go.layout.Annotation(
        x=r_opt,
        y=min_e2e_deadline,
        xref="x",
        yref="y",
        text=annot_text,
        arrowhead=6,
        arrowwidth=1,
        arrowsize=2,
        ax=-350,
        ay=-75,
        bordercolor="black",
        borderpad=15,
        bgcolor=colors.light_orange,
        # showarrow=False,
        # xanchor='left'
    )
    notes.append(min_dead_annot)
    min_dead_value = go.layout.Annotation(
        x=r_opt,
        y=min_e2e_deadline,
        xref="x",
        yref="y",
        text="%0.2f s" % min_e2e_deadline,
        font={'size': 22},
        ax=-350,
        ay=-63,
        showarrow=True,
        arrowcolor='rgba(255, 182, 193, .0)',
    )
    notes.append(min_dead_value)

    # y axis title
    ytitle = go.layout.Annotation(x=0,
                                  y=1.15,
                                  xref="paper",
                                  yref="paper",
                                  text="End-to-end deadline [s]",
                                  showarrow=False,
                                  xanchor='left')
    notes.append(ytitle)

    default_layout = go.Layout(
        xaxis={
            'title': 'Deadline ratio [ . ]',
        },
        # yaxis={'ticksuffix':"  "},
        annotations=notes,
        shapes=shapes,
        yaxis={'range': [0, max(y_max)]},
        legend={
            'bgcolor': 'white',
            'xanchor': 'right',
            'x': 0.97,
            'yanchor': 'top',
            'y': 0.95,
            'borderwidth': 5,
            'bordercolor': 'white',
        })
    fig.update_layout(default_layout)

    return fig
Ejemplo n.º 17
0
def update_graph(ego):
    edge_x = []
    edge_y = []
    for edge in G.edges():
        x0, y0 = G.nodes[edge[0]]['pos']
        x1, y1 = G.nodes[edge[1]]['pos']
        edge_x.append(x0)
        edge_x.append(x1)
        edge_x.append(None)
        edge_y.append(y0)
        edge_y.append(y1)
        edge_y.append(None)

    edge_trace = go.Scatter(x=edge_x,
                            y=edge_y,
                            line=dict(width=0.5, color='#888'),
                            hoverinfo='none',
                            mode='lines')

    node_x = []
    node_y = []
    for node in G.nodes():
        x, y = G.nodes[node]['pos']
        node_x.append(x)
        node_y.append(y)

    node_trace = go.Scatter(x=node_x,
                            y=node_y,
                            mode='markers',
                            hoverinfo='text',
                            marker=dict(showscale=True,
                                        colorscale='Electric',
                                        reversescale=True,
                                        color=[],
                                        size=10,
                                        colorbar=dict(
                                            thickness=15,
                                            title='Pacotes conectados',
                                            xanchor='left',
                                            titleside='right'),
                                        line_width=2))

    node_adjacencies = []
    node_text = []
    for node, adjacencies in enumerate(G.adjacency()):
        node_adjacencies.append(len(adjacencies[1]))
        node_text.append(str(len(adjacencies[1])) + ' conexões')

    node_trace.marker.color = node_adjacencies
    node_trace.text = node_text
    node_trace.marker.size = node_adjacencies
    fig = go.Figure(
        data=[edge_trace, node_trace],
        layout=go.Layout(
            title='<br>Grafo de dependência Python',
            titlefont_size=16,
            showlegend=False,
            hovermode='closest',
            margin=dict(b=20, l=5, r=5, t=40),
            annotations=[
                dict(text="Grafo de rede de dependência de pacotes Python",
                     showarrow=False,
                     xref="paper",
                     yref="paper",
                     x=0.005,
                     y=-0.002)
            ],
            xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
            yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))

    return fig
Ejemplo n.º 18
0
def DRP_hist(x, annot_size=16):

    # Vertical positioning of annotations
    top_annot = 0.95
    second_annot = 0.75

    max_latency_ratio = max(x)

    fig = go.Figure()

    fig.add_trace(
        go.Histogram(
            x=x,
            histnorm='percent',
            nbinsx=50,
            marker_color=colors.light_orange,
        ))

    notes = []
    shapes = []

    # Analytical bound
    note = go.layout.Annotation(
        x=100,
        y=top_annot,
        xref="x",
        yref="paper",
        text="Analytical bound",
        showarrow=False,
        # font=dict(
        #     size=annot_size,
        # ),
        xanchor='right',
        xshift=-10)
    notes.append(note)
    line = go.layout.Shape(type="line",
                           xref="x",
                           x0=100,
                           x1=100,
                           yref="paper",
                           y0=0,
                           y1=top_annot,
                           line=dict(
                               color=colors.red,
                               width=3,
                           ))
    shapes.append(line)

    # Reached bound
    note = go.layout.Annotation(
        x=max_latency_ratio,
        y=second_annot,
        xref="x",
        yref="paper",
        text=("%2.0f%%" % max_latency_ratio),
        showarrow=False,
        # font=dict(
        #     size=annot_size,
        # ),
        xanchor='right',
        xshift=-10)
    notes.append(note)
    line = go.layout.Shape(type="line",
                           xref="x",
                           x0=max_latency_ratio,
                           x1=max_latency_ratio,
                           yref="paper",
                           y0=0,
                           y1=second_annot,
                           line=dict(
                               color=colors.red,
                               width=3,
                               dash="dot",
                           ))
    shapes.append(line)

    ytitle = go.layout.Annotation(
        x=0,
        y=1.25,
        xref="paper",
        yref="paper",
        text="Percentage of messages [%]",
        showarrow=False,
        xanchor='left',
    )
    notes.append(ytitle)

    # Default Layout
    default_layout = go.Layout(
        xaxis={
            'title': 'End-to-end latency of messages  [ % of analytic bound ]',
            'range': [-1, 105],
            'zeroline': True
        },
        yaxis={
            'ticksuffix': "  ",
            'zeroline': True
        },
        annotations=notes,
        shapes=shapes,
    )
    fig.update_layout(default_layout)

    return fig
    print(tweet_text_df['user_name'].value_counts())

    temp = pd.DataFrame(
        {'user_name_count': tweet_text_df['user_name'].value_counts()})
    df = temp[temp.user_name_count > 5]
    df = df.sort_values(by='user_name_count',
                        ascending=False,
                        na_position="last")
    data = go.Data(
        [go.Bar(
            x=df.index,
            y=df.user_name_count,
            orientation='v',
        )])
    layout = go.Layout(title="Usuarios con mayor cantidad de Tweets")
    fig = go.Figure(data=data, layout=layout)
    fig.show()

    # ############################################################# timeline
    # segunda parte: por cada usuario buscar la linea de tiempo

    user_timeline_filename = 'user_timeline_filename_'
    user_timeline_filtered_filename = 'user_timeline_filtered_filename_'

    dictionary_user_tweets = {}

    for user in df.index:
        # inicializar listas
        tweets_per_user = []
        tweets_per_user_filtered = []
Ejemplo n.º 20
0
def PairwiseDensityPlot(df,
                        X=None,
                        Y=None,
                        scatter=True,
                        width=800,
                        height=800):

    if not X:
        X = df.select_dtypes(
            include=['bool', 'float', 'int', 'category']).columns.values

    if not Y:
        Y = df.select_dtypes(
            include=['bool', 'float', 'int', 'category']).columns.values

    assert Basic.isCollection(
        X
    ), "X needs to be a collection type. If inputting only a single value, add it as a list."
    assert Basic.isCollection(
        Y
    ), "Y needs to be a collection type. If inputting only a single value, add it as a list."

    x = df[X[0]].values
    y = df[Y[0]].values

    x_dropdown = widgets.Dropdown(
        options=X,
        value=X[0],
        description='X Axis Value:',
    )

    y_dropdown = widgets.Dropdown(
        options=Y,
        value=Y[0],
        description='Y Axis Value:',
    )

    container = widgets.HBox([x_dropdown, y_dropdown])

    #start of figure
    traces = []

    traces.append(
        go.Histogram2dContour(x=x,
                              y=y,
                              colorscale='Blues',
                              reversescale=True,
                              xaxis='x',
                              yaxis='y',
                              name='Contour',
                              showscale=False))

    if scatter:
        #with enough datapoints, this will slow down the graph build or make it look fugly.
        traces.append(
            go.Scatter(x=x,
                       y=y,
                       xaxis='x',
                       yaxis='y',
                       mode='markers',
                       marker=dict(color='rgba(0,0,0,0.2)', size=2),
                       name='Data',
                       hoverinfo='skip'))

    traces.append(
        go.Histogram(y=y,
                     xaxis='x2',
                     marker=dict(color='rgba(0,0,0,1)'),
                     name='Histogram',
                     orientation='h'))
    traces.append(
        go.Histogram(x=x,
                     yaxis='y2',
                     marker=dict(color='rgba(0,0,0,1)'),
                     name='Histogram'))
    layout = go.Layout(autosize=True,
                       width=width,
                       height=height,
                       xaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=False),
                       yaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=False),
                       xaxis2=dict(zeroline=False,
                                   domain=[0.85, 1],
                                   showgrid=False),
                       yaxis2=dict(zeroline=False,
                                   domain=[0.85, 1],
                                   showgrid=False),
                       bargap=0,
                       showlegend=False,
                       margin=dict(l=10, r=10, t=10, b=10))

    g = go.FigureWidget(data=traces, layout=layout)

    def response(change):
        x = df[x_dropdown.value].values
        y = df[y_dropdown.value].values

        update_range = 4 if scatter else 3
        yhist = 1 if scatter else 2

        with g.batch_update():
            for i in range(0, update_range):
                g.data[i].x = x
                g.data[i].y = y
                g.layout.xaxis.title = x_dropdown.value
                g.layout.yaxis.title = y_dropdown.value

    x_dropdown.observe(response, names="value")
    y_dropdown.observe(response, names="value")

    Title(
        title="Interactive Density Plot",
        description="Select values for X and Y axis to view varying densities."
    )
    display(widgets.VBox([container, g]))

    return
Ejemplo n.º 21
0
tabtitle = 'beer!'
myheading = 'Flying Dog Beers'
label1 = 'IBU'
label2 = 'ABV'
githublink = 'https://github.com/austinlasseter/flying-dog-beers'
sourceurl = 'https://www.flyingdog.com/beers/'

########### Set up the chart
bitterness = go.Bar(x=beers,
                    y=ibu_values,
                    name=label1,
                    marker={'color': color1})
alcohol = go.Bar(x=beers, y=abv_values, name=label2, marker={'color': color2})

beer_data = [bitterness, alcohol]
beer_layout = go.Layout(barmode='group', title=mytitle)

beer_fig = go.Figure(data=beer_data, layout=beer_layout)

########### Initiate the app
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
app.title = tabtitle

########### Set up the layout
app.layout = html.Div(children=[
    html.H1(myheading),
    dcc.Graph(id='flyingdog', figure=beer_fig),
    html.A('Code on Github', href=githublink),
    html.Br(),
Ejemplo n.º 22
0
                 xref='x',
                 yref='y',
                 line_width=1)
        ]

        #print(anno)
        fig = go.Figure(data=[
            go.Candlestick(x=cht_timestamp,
                           open=cht_open,
                           high=cht_high,
                           low=cht_low,
                           close=cht_close)
        ],
                        layout=go.Layout(title=go.layout.Title(
                            text=f"{symbol} - {rec_cht}"),
                                         shapes=thresh,
                                         annotations=anno,
                                         yaxis_title="Price per Share (USD)"))

        fig.show()

    else:  #IF TICKER NOT FOUND ON API

        if error_check == "Error Message":
            failed_tickers.append({
                'ticker': tkr,
                'err_type': 'Invalid API Call'
            })

        elif error_check == "Note":
            failed_tickers.append({
Ejemplo n.º 23
0
def graph(g: nx.Graph, s: Optional[list] = None, plot_size: int = 500):  # pragma: no cover
    """Creates a plot of the input graph.

    This function can plot the input graph only, or the graph with a specified subgraph highlighted.

    **Example usage:**

    >>> graph = nx.complete_graph(10)
    >>> fig = graph(graph, [0, 1, 2, 3])
    >>> fig.show()

    .. image:: ../../_static/complete_graph.png
       :width: 40%
       :align: center
       :target: javascript:void(0);

    Args:
        g (nx.Graph): input graph
        s (list): optional list of nodes comprising the subgraph to highlight
        plot_size (int): size of the plot in pixels, rendered in a square layout

    Returns:
         Figure: figure for graph and optionally highlighted subgraph
    """
    try:
        import plotly.graph_objects as go
    except ImportError:
        raise ImportError(plotly_error)

    l = nx.kamada_kawai_layout(g)

    g_nodes = go.Scatter(
        **_node_coords(g, l),
        mode="markers",
        hoverinfo="text",
        marker=dict(color=graph_node_colour, size=graph_node_size, line_width=2),
    )

    g_edges = go.Scatter(
        **_edge_coords(g, l),
        line=dict(width=1, color=graph_edge_colour),
        hoverinfo="none",
        mode="lines",
    )

    g_nodes.text = [str(i) for i in g.nodes()]

    layout = go.Layout(
        showlegend=False,
        hovermode="closest",
        xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        margin=dict(b=0, l=0, r=0, t=25),
        height=plot_size,
        width=plot_size,
        plot_bgcolor="#ffffff",
    )

    if s is not None:
        s = g.subgraph(s)

        s_edges = go.Scatter(
            **_edge_coords(s, l),
            line=dict(width=2, color=subgraph_edge_colour),
            hoverinfo="none",
            mode="lines",
        )

        s_nodes = go.Scatter(
            **_node_coords(s, l),
            mode="markers",
            hoverinfo="text",
            marker=dict(color=subgraph_node_colour, size=subgraph_node_size, line_width=2),
        )

        s_nodes.text = [str(i) for i in s.nodes()]

        f = go.Figure(data=[g_edges, s_edges, g_nodes, s_nodes], layout=layout)

    else:
        f = go.Figure(data=[g_edges, g_nodes], layout=layout)

    return f
Ejemplo n.º 24
0
def main():

    # Settings.
    scenario_name = 'singapore_all'
    results_path = fledge.utils.get_results_path(__file__, scenario_name)

    # Recreate / overwrite database, to incorporate changes in the CSV files.
    fledge.data_interface.recreate_database()

    # Obtain electric grid data / graph.
    electric_grid_data = fledge.data_interface.ElectricGridData(scenario_name)
    electric_grid_graph = fledge.plots.ElectricGridGraph(scenario_name)

    # Obtain substation nodes.
    # - This identification is based on the assumption that all nodes with no DER connected are substation nodes,
    #   which is true for the Singapore synthetic grid test case.
    nodes_substation = (electric_grid_data.electric_grid_transformers.loc[
        electric_grid_data.electric_grid_transformers.
        loc[:, 'transformer_name'].str.contains('66kV'), 'node_2_name'].values)

    # Obtain values.
    nodes_values = (pd.DataFrame(electric_grid_graph.node_positions).T.rename(
        {
            0: 'longitude',
            1: 'latitude'
        }, axis='columns'))
    lines = pd.DataFrame(electric_grid_graph.edges)
    lines_values = pd.DataFrame(index=range(3 * len(lines)),
                                columns=['longitude', 'latitude'])
    lines_values.loc[range(0, 3 * len(lines), 3), :] = nodes_values.reindex(
        lines.iloc[:, 0]).values
    lines_values.loc[range(1, 3 * len(lines), 3), :] = nodes_values.reindex(
        lines.iloc[:, 1]).values
    lines_values.loc[range(2, 3 * len(lines), 3), :] = np.full((len(lines), 2),
                                                               np.nan)

    # Obtain latitude / longitude bounds.
    longitude_max = nodes_values.loc[:, 'longitude'].max()
    longitude_min = nodes_values.loc[:, 'longitude'].min()
    latitude_max = nodes_values.loc[:, 'latitude'].max()
    latitude_min = nodes_values.loc[:, 'latitude'].min()

    # Obtain zoom / center for interactive plot.
    zoom_longitude = np.log2(360 * 2.0 / (longitude_max - longitude_min))
    zoom_latitude = np.log2(360 * 2.0 / (latitude_max - latitude_min))
    zoom_correction = 1.035
    zoom = zoom_correction * np.min([zoom_longitude, zoom_latitude])
    center = dict(lon=0.5 * (longitude_max + longitude_min),
                  lat=0.5 * (latitude_max + latitude_min))

    # Obtain background map image for static plot.
    image_bounds = (longitude_min, latitude_min, longitude_max, latitude_max)
    image, image_bounds = (ctx.bounds2img(
        *image_bounds, zoom=14, source=ctx.providers.CartoDB.Positron,
        ll=True))
    # Reorder image bounds, because it's jumbled up in bounds2img. # TODO: Raise issue.
    image_bounds = (image_bounds[0], image_bounds[2], image_bounds[1],
                    image_bounds[3])
    image_bounds = (rasterio.warp.transform_bounds({'init': 'epsg:3857'},
                                                   {'init': 'epsg:4326'},
                                                   *image_bounds))
    width, height = image.shape[1], image.shape[0]
    image = PIL.Image.fromarray(image)

    # Create static plot.
    figure = go.Figure()
    figure.add_trace(
        go.Scatter(x=lines_values.loc[:, 'longitude'],
                   y=lines_values.loc[:, 'latitude'],
                   line=dict(color='black', width=0.25),
                   hoverinfo='none',
                   mode='lines'))
    figure.add_trace(
        go.Scatter(x=nodes_values.loc[:, 'longitude'],
                   y=nodes_values.loc[:, 'latitude'],
                   text=list(electric_grid_graph.nodes),
                   mode='markers+text',
                   hoverinfo='none',
                   marker=dict(color='lightskyblue', size=4),
                   textfont=dict(size=1)))
    figure.add_trace(
        go.Scatter(x=nodes_values.loc[nodes_substation, 'longitude'],
                   y=nodes_values.loc[nodes_substation, 'latitude'],
                   text=nodes_substation,
                   mode='markers+text',
                   hoverinfo='none',
                   marker=dict(color='lightpink', size=4),
                   textfont=dict(size=1)))
    figure.add_layout_image(
        dict(source=image,
             xref='x',
             yref='y',
             x=image_bounds[0],
             y=image_bounds[1],
             sizex=image_bounds[2] - image_bounds[0],
             sizey=image_bounds[3] - image_bounds[1],
             xanchor='left',
             yanchor='bottom',
             sizing='stretch',
             opacity=1.0,
             layer='below'))
    figure.update(
        layout=go.Layout(width=width,
                         height=height,
                         showlegend=False,
                         hovermode='closest',
                         margin=dict(b=0, l=0, r=0, t=0),
                         xaxis=go.layout.XAxis(showgrid=False,
                                               zeroline=False,
                                               showticklabels=False,
                                               ticks='',
                                               range=(image_bounds[0],
                                                      image_bounds[2])),
                         yaxis=dict(showgrid=False,
                                    zeroline=False,
                                    showticklabels=False,
                                    ticks='',
                                    scaleanchor='x',
                                    scaleratio=1,
                                    range=(image_bounds[1], image_bounds[3]))))
    figure.write_image(os.path.join(results_path, 'electric_grid.pdf'))
    fledge.utils.launch(os.path.join(results_path, 'electric_grid.pdf'))

    # Create interactive plot.
    figure = go.Figure()
    figure.add_trace(
        go.Scattermapbox(lon=lines_values.loc[:, 'longitude'],
                         lat=lines_values.loc[:, 'latitude'],
                         line=dict(color='black', width=0.5),
                         hoverinfo='none',
                         mode='lines'))
    figure.add_trace(
        go.Scattermapbox(
            lon=nodes_values.loc[:, 'longitude'],
            lat=nodes_values.loc[:, 'latitude'],
            text=('Node: ' +
                  np.array(electric_grid_graph.nodes, dtype=object)),
            mode='markers',
            hoverinfo='text',
            marker=dict(color='royalblue')))
    figure.add_trace(
        go.Scattermapbox(lon=nodes_values.loc[nodes_substation, 'longitude'],
                         lat=nodes_values.loc[nodes_substation, 'latitude'],
                         text=('Substation: ' + nodes_substation),
                         mode='markers',
                         hoverinfo='text',
                         marker=dict(color='crimson')))
    figure.update(layout=go.Layout(
        showlegend=False,
        hovermode='closest',
        margin=dict(b=0, l=0, r=0, t=0),
        mapbox=go.layout.Mapbox(
            style='carto-positron', zoom=zoom, center=center),
        xaxis=go.layout.XAxis(
            showgrid=False, zeroline=False, showticklabels=False, ticks=''),
        yaxis=dict(
            showgrid=False, zeroline=False, showticklabels=False, ticks='')))
    figure.write_html(os.path.join(results_path, 'electric_grid.html'))
    fledge.utils.launch(os.path.join(results_path, 'electric_grid.html'))

    # Print results path.
    fledge.utils.launch(results_path)
    print(f"Results are stored in: {results_path}")
Ejemplo n.º 25
0
def display_(userId_value):
    if userId_value == None:
        df_10_ft = data_10_frequency_timespent
        df_11_ft = data_11_frequency_timespent
    else:
        df_10_ft = data_10_frequency_timespent[
            data_10_frequency_timespent["userId"] == userId_value]
        df_11_ft = data_11_frequency_timespent[
            data_11_frequency_timespent["userId"] == userId_value]

    trace_frequency_10 = go.Bar(x=df_10_ft.actionName,
                                y=df_10_ft.frequency,
                                name="Odoo 10",
                                marker=dict(color='rgba(0, 190, 224, 0.95)',
                                            line=dict(color='rgb(0,0,0)',
                                                      width=1.5)),
                                text=data_10_frequency_timespent.frequency)
    # create trace_frequency_11
    trace_frequency_11 = go.Bar(x=df_11_ft.actionName,
                                y=df_11_ft.frequency,
                                name="Odoo 11",
                                marker=dict(color='rgba(252, 69, 53, 0.95)',
                                            line=dict(color='rgb(0,0,0)',
                                                      width=1.5)),
                                text=data_11_frequency_timespent.frequency)

    data_frequency = [trace_frequency_10, trace_frequency_11]
    layout_frequency = go.Layout(barmode="group",
                                 height=600,
                                 title="Frequency")
    fig_frequency = go.Figure(data=data_frequency, layout=layout_frequency)

    trace_timespent_10 = go.Bar(x=df_10_ft.actionName,
                                y=df_10_ft.timespent,
                                name="Odoo 10",
                                marker=dict(color='rgba(255, 167, 5, 0.95)',
                                            line=dict(color='rgb(0,0,0)',
                                                      width=1.5)),
                                text=data_10_frequency_timespent.timespent)

    trace_timespent_11 = go.Bar(x=df_11_ft.actionName,
                                y=df_11_ft.timespent,
                                name="Odoo 11",
                                marker=dict(color='rgba(0, 204, 132, 0.95)',
                                            line=dict(color='rgb(0,0,0)',
                                                      width=1.5)),
                                text=data_11_frequency_timespent.timespent)

    data_timespent = [trace_timespent_10, trace_timespent_11]
    layout_timespent = go.Layout(barmode="group",
                                 height=600,
                                 title="Time Spent")
    fig_timespent = go.Figure(data=data_timespent, layout=layout_timespent)

    # Plot figures for Consistency measures
    fig_consistency_frequency = px.histogram(data_consistency,
                                             x="actionName",
                                             y="consistency_frequency",
                                             color="userId",
                                             marginal="box",
                                             height=900,
                                             title="Consistency of Frequency")

    fig_consistency_timespent = px.histogram(data_consistency,
                                             x="actionName",
                                             y="consistency_timespent",
                                             color="userId",
                                             marginal="box",
                                             height=900,
                                             title="Consistency of Time Spent")
    #iplot(fig)
    return fig_frequency, fig_timespent, fig_consistency_frequency, fig_consistency_timespent
Ejemplo n.º 26
0
	subvals[i] = val1 - val2
	print(subvals[i])
	#print(pTvals2d[i])
#print()


data1 = {'times2d': reltimes2d, 'pT values': pTvals2d, 'subvals': subvals}
data2 = {'times3d': reltimes3d, 'B values': Bvals3d}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# Assign an empty figure widget with two traces
trace1 = go.Scatter(x=df1['times2d'], y=df1['pT values'], opacity=0.75, name='2D Plate Mapper')
trace2 = go.Scatter(x=df2['times3d'], y=df2['B values'], opacity=0.75, name='3D Bartington Mapper')
trace3 = go.Scatter(x=df1['times2d'], y=df1['subvals'], opacity=0.75, name='2D - 3D')
g = go.FigureWidget(data=[trace1, trace2],
                    layout=go.Layout(
                        title=dict(
                            text='Background Maps'
                        ),
                        barmode='overlay'
                    ))

g.show()
#print(subvals)




# (t-datetime.datetime(1970,1,1)).total_seconds()

# open the files again, parse the data, populate an array with (file time- origin time).totalseconds
Ejemplo n.º 27
0
def TTW_hist(x, KPI, max_model):

    # Vertical positioning of annotations
    top_annot = 0.95
    second_annot = 0.5


    max_observed = max(x)

    fig = go.Figure()

    fig.add_trace(
        go.Histogram(
            x=x,
            histnorm='percent',
            # nbinsx=50,
            marker_color=colors.accent[0]['normal'],
        )
    )

    notes = []
    shapes = []

    # Analytical bound
    note = go.layout.Annotation(
            x=max_model,
            y=top_annot,
            xref="x",
            yref="paper",
            text="Model",
            showarrow=False,
            xanchor='right',
            xshift=-10
        )
    notes.append(note)
    line = go.layout.Shape(
            type="line",
            xref="x",
            x0=max_model,
            x1=max_model,
            yref="paper",
            y0=0,
            y1=top_annot,
            line=dict(
                color=colors.red,
                width=3,
            )
        )
    shapes.append(line)

    # Reached bound
    note = go.layout.Annotation(
            x=max_observed,
            y=second_annot,
            xref="x",
            yref="paper",
            text=("%2.2f ms" % max_observed),
            showarrow=False,
            xanchor='left',
            xshift=10,
            yshift=-10
        )
    notes.append(note)
    line = go.layout.Shape(
            type="line",
            xref="x",
            x0=max_observed,
            x1=max_observed,
            yref="paper",
            y0=0,
            y1=second_annot,
            line=dict(
                color=colors.red,
                width=3,
                dash="dot",
            )
        )
    shapes.append(line)

    ytitle = go.layout.Annotation(
            x=0,
            y=1.25,
            xref="paper",
            yref="paper",
            text="Number of samples [%]",
            showarrow=False,
            xanchor='left',
        )
    notes.append(ytitle)

    # Default Layout
    default_layout = go.Layout(
        annotations=notes,
        shapes=shapes,
        )
    fig.update_layout(default_layout)

    return fig
Ejemplo n.º 28
0
def subgraph(s: nx.Graph, plot_size: Tuple = (500, 500)):  # pragma: no cover
    """Creates a plot of the input subgraph.

    Subgraphs are plotted using the Kamada-Kawai layout with an aspect ratio of 1:1.

    **Example usage:**

    >>> graph = nx.complete_graph(10)
    >>> subgraph = graph.subgraph([0, 1, 2, 3])
    >>> fig = plot.subgraph(subgraph)
    >>> fig.show()

    .. image:: ../../_static/complete_subgraph.png
       :width: 40%
       :align: center
       :target: javascript:void(0);

    Args:
        s (nx.Graph): input subgraph
        plot_size (int): size of the plot in pixels, given as a pair of integers ``(x_size,
            y_size)``

    Returns:
         Figure: figure for subgraph
    """
    try:
        import plotly.graph_objects as go
    except ImportError:
        raise ImportError(plotly_error)

    l = nx.kamada_kawai_layout(s)

    g_edges = go.Scatter(
        **_edge_coords(s, l),
        line=dict(width=1.5, color=subgraph_edge_colour),
        hoverinfo="none",
        mode="lines",
    )

    g_nodes = go.Scatter(
        **_node_coords(s, l),
        mode="markers",
        hoverinfo="text",
        marker=dict(color=subgraph_node_colour,
                    size=graph_node_size,
                    line_width=2),
    )

    g_nodes.text = [str(i) for i in s.nodes()]

    layout = go.Layout(
        showlegend=False,
        hovermode="closest",
        xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        margin=dict(b=0, l=0, r=0, t=25),
        height=plot_size[1],
        width=plot_size[0],
        plot_bgcolor="#ffffff",
    )

    f = go.Figure(data=[g_edges, g_nodes], layout=layout)

    return f
Ejemplo n.º 29
0
    def topic_graph(self) -> go.Figure:
        # @title Topic Analysis
        # @markdown What are the things you commonly talk about? What are things you've been avoiding? \
        # @markdown Note that the **entity extraction is shaky** because the sentences are so small,
        # but should still be good enough to give a general idea about the topics discussed \
        # @markdown \
        # @markdown The *Topic Graph* is the most informative and comprehensive visualizations,
        # but I've also included some word clouds if graphs aren't your thing.
        # The generated graph will be slightly different each time

        topic_graph = nx.Graph()
        entity_label = "entity_label"
        weight = "weight"

        # Let's generate a graph of the topics discussed
        topic_graph.add_nodes_from(
            self.participants, entity_label=PARTICIPANTS_LABEL
        )
        for i_df, participant in zip(self.dfs, self.participants):
            for entities in i_df[ENTITIES].values:
                for text, label in entities.items():
                    topic_graph.add_node(text, entity_label=label)
                    if topic_graph.has_edge(participant, text):
                        topic_graph[participant][text][weight] += 1
                    else:
                        topic_graph.add_edge(participant, text, weight=1)

        # Remove isolated nodes (can happen when there's an incorrect number of senders)
        topic_graph.remove_nodes_from(list(nx.isolates(topic_graph)))

        # Map each entity label to some random color
        topic_color_map = {
            label: random_color() for label in SIMPLIFIED_LABELS
        }

        # Generate the positions for node plotting based on edge weights
        node_positions = nx.spring_layout(topic_graph)

        # Generate the edge plot
        edge_x = []
        edge_y = []
        for edge in topic_graph.edges():
            x0, y0 = node_positions[edge[0]]
            x1, y1 = node_positions[edge[1]]
            edge_x.append(x0)
            edge_x.append(x1)
            edge_x.append(None)
            edge_y.append(y0)
            edge_y.append(y1)
            edge_y.append(None)

        edge_trace = go.Scatter(
            x=edge_x,
            y=edge_y,
            line=dict(width=0.5, color="#888"),
            name="Talks about",
            hoverinfo="none",
            mode="lines",
        )

        # Function for mapping node weights to sizes
        def map_size(weight_degree: int) -> int:
            if weight_degree == 1:
                return 10
            elif weight_degree <= 10:
                return 20
            elif weight_degree <= 100:
                return 30
            else:
                return 40

        node_traces = []
        for label in SIMPLIFIED_LABELS:
            node_x = []
            node_y = []
            for node in topic_graph.nodes():
                if label != topic_graph.nodes[node][entity_label]:
                    continue
                x, y = node_positions[node]
                node_x.append(x)
                node_y.append(y)

            node_trace = go.Scatter(
                x=node_x,
                y=node_y,
                name=label,
                mode="markers",
                hoverinfo="text",
                marker={"color": topic_color_map[label], "line_width": 2},
            )

            node_colors, node_weights, node_text = [], [], []
            for adjacencies in topic_graph.adjacency():
                node_weight = 0
                if topic_graph.nodes[adjacencies[0]][entity_label] != label:
                    continue
                for adjacency in adjacencies[1].values():
                    node_weight += adjacency[weight]
                node_weights.append(node_weight)
                node_text.append(
                    "<b>{}</b> <br>Discussion Frequency: {}".format(
                        adjacencies[0], node_weight
                    )
                )

            node_trace.marker.size = list(
                map(lambda m: map_size(m), node_weights)
            )
            node_trace.text = node_text
            node_traces.append(node_trace)

        fig = go.Figure(
            data=[edge_trace, *node_traces],
            layout=go.Layout(
                title="<br>Topic Graph 📚",
                titlefont_size=self.title_size,
                hovermode="closest",
                margin=dict(b=20, l=5, r=5, t=40),
                height=750,
                annotations=[
                    dict(
                        text="To learn how these were extracted, checkout "
                        "<a href='https://spacy.io/usage/linguistic-features/#named-entities'>Spacy</a>",
                        showarrow=False,
                        xref="paper",
                        yref="paper",
                        x=0.005,
                        y=-0.002,
                    )
                ],
                xaxis=self.hide_axis_dict,
                yaxis=self.hide_axis_dict,
            ),
        )

        return fig
Ejemplo n.º 30
0
                            (encuestas.Facultad == "Veterinaria"),
                            'Respuesta_texto'].value_counts().reset_index()

######################
#3 Creando el grafico#
######################

#Facultades
trace_1 = go.Pie(labels=Pregunta_1.loc[:, 'index'],
                 values=Pregunta_1.loc[:, 'Respuesta_texto'])
layout_1 = go.Layout(legend={
    "x": 0,
    "y": -.5
},
                     margin=dict(
                         l=23,
                         r=18,
                         b=53,
                         t=73,
                     ),
                     paper_bgcolor='rgb(223, 223, 223)',
                     template='ggplot2')
fig_1 = go.Figure(data=[trace_1], layout=layout_1)

trace_2 = go.Pie(labels=Pregunta_2.loc[:, 'index'],
                 values=Pregunta_2.loc[:, 'Respuesta_texto'])
layout_2 = go.Layout(legend={
    "x": 0,
    "y": -.5
},
                     margin=dict(
                         l=15,