def update_triplot(tabs, dp1, dp2, dp3, dp4, nameform, contents): import plotly.express as px if tabs == 'graphic-table': if contents == None: return relative_filename = nameform df = pd.read_excel(relative_filename) if 'Total' in df.columns: fig = px.scatter_ternary(df, a=df[dp1], b=df[dp2], c=df[dp3], size_max=15, color=dp4, hover_name=df['PREDICTED MINERAL'], size=df['Total']) else: fig = px.scatter_ternary(df, a=df[dp1], b=df[dp2], c=df[dp3], size_max=15, color=dp4, hover_name=df['PREDICTED MINERAL']) return html.Div([dcc.Graph(figure=fig)]) else: return None
def plot_3d(self, path): colsets = list(it.combinations(range(8), 3)) for colset in colsets: colnames = dict(zip(['a','b','c'], ['C_{}'.format(x) for x in colset])) ppc = pd.DataFrame(self.generate_posterior_predictive_simplex_3d(colset), columns = [colnames[x] for x in ['a','b','c']]) ppc['source'] = 'PostPred' emc = pd.DataFrame(self.data.Yl[:,colset], columns = [colnames[x] for x in ['a','b','c']]) emc['source'] = 'Empirical' out_df = pd.concat([emc, ppc], axis = 0) fig = px.scatter_ternary(out_df, color = 'source', **colnames) fig.write_image(os.path.join(path, self.png_name.format(*colset))) del(fig) del(emc) del(ppc) return
def plot_sentiments_with_ternary(tweets: List[TweetData], show: bool = False, group: str = ""): # draw ternary plot negative_count = [] neutral_count = [] positive_count = [] # This is really slow to instance, need to define outside of tweet class analyser = SentimentIntensityAnalyzer() sentiments = { "NEGATIVE": [], "NEUTRAL": [], "POSITIVE": [], } for tweet in tweets: sentiment = tweet.set_sentiment_value(analyser) if sentiment is Sentiment.NEGATIVE: negative_count.append(tweet.sentiment_value) elif sentiment is Sentiment.POSITIVE: positive_count.append(tweet.sentiment_value) elif sentiment is Sentiment.NEUTRAL: neutral_count.append(tweet.sentiment_value) sentiments["NEGATIVE"].append(tweet.sentiment_value.get("neg")) sentiments["NEUTRAL"].append(tweet.sentiment_value.get("neu")) sentiments["POSITIVE"].append(tweet.sentiment_value.get("pos")) GLOBAL_LOGGER.debug("Sentiment calculation done.") GLOBAL_LOGGER.info(f"Length of negative: {len(negative_count)}") GLOBAL_LOGGER.info(f"Length of neutral: {len(neutral_count)}") GLOBAL_LOGGER.info(f"Length of positive: {len(positive_count)}") df = pandas.DataFrame(sentiments) fig = px.scatter_ternary(df, b="NEGATIVE", a="NEUTRAL", c="POSITIVE") name = group if group else "all" path = f"article/figures/sentiment_ternary_{name}.png" GLOBAL_LOGGER.info( f"Writing ternary plot of sentiment analysis into path {path}") fig.write_image(path) if show: fig.show()
img = data.camera() fig = px.imshow(img, color_continuous_scale='gray') fig.add_trace( go.Contour(z=img, showscale=False, contours=dict(start=0, end=70, size=70, coloring='lines'), line_width=2)) fig.add_trace(go.Scatter(x=[230], y=[100], marker=dict(color='red', size=16))) fig.show() # In[ ]: import plotly.express as px df = px.data.election() fig = px.scatter_ternary(df, a="Joly", b="Coderre", c="Bergeron") fig.show() # In[ ]: import plotly.express as px df = px.data.election() fig = px.scatter_ternary(df, a="Joly", b="Coderre", c="Bergeron", hover_name="district", color="winner", size="total", size_max=15,
def fig_14(): fig = px.scatter_ternary(df_MPG, a="SAT (%)", b="ARO (%)", c="POL (%)", color="Stratigraphic unit", symbol="Facies", size="Locality_size", size_max=8, template="simple_white", color_discrete_map={ "Lower-Middle Muen Mb": '#F0E442', 'Upper Muen Mb': "#E69F00", "Lower Blanknuten Mb": "#56B4E9", "Middle Blanknuten Mb": "#009E73", "Upper Blanknuten Mb": "#0072B2", "Tschermakfjellet Fm": "#CC79A7", }) fig.update_traces(marker=dict(opacity=0.9, line=dict(width=0.5, color='black')), selector=dict(mode='markers')) def makeAxis(title, tickangle): return { 'title': title, 'titlefont': { 'size': 20 }, 'tickangle': tickangle, 'tickfont': { 'size': 10 }, 'tickcolor': 'rgba(0,0,0,0)', 'ticklen': 5, 'showline': True, # 'showgrid': True } fig.update_layout({ 'ternary': { 'sum': 100, #'aaxis': makeAxis('SAT %', 0), #'baxis': makeAxis('<br>ARO %', 45), #'caxis': makeAxis('<br>POL %', -45) }, 'annotations': [{ 'showarrow': False, 'text': 'Simple Ternary Plot with Markers', 'x': 0.5, 'y': 1.3, 'font': { 'size': 15 } }] }) fig.update_ternaries(caxis_min=45) fig.show() fig.write_image("Fig_14_UNEDITED.pdf")
def processAlgorithm(self, parameters, context, feedback): Grid = self.parameterAsVectorLayer(parameters, self.Grid, context) try: import pandas as pd import plotly.graph_objs as go import plotly.express as px import chart_studio.plotly as py except Exception: feedback.reportError(QCoreApplication.translate('Error','%s'%(e))) feedback.reportError(QCoreApplication.translate('Error',' ')) feedback.reportError(QCoreApplication.translate('Error','Error loading modules - please install the necessary dependencies')) return {} X = self.parameterAsString(parameters, self.X, context) Y = self.parameterAsString(parameters, self.Y, context) Z = self.parameterAsString(parameters, self.Z, context) S = self.parameterAsString(parameters, self.Size, context) T = self.parameterAsString(parameters, self.Time, context) G = self.parameterAsString(parameters, self.Grp, context) speed = parameters[self.Speed] A = parameters[self.A] if A and T == '': feedback.reportError(QCoreApplication.translate('Error','Error - Please select a Time Field for animations.')) return {} names = [X,Y,Z,S,T,G] vNames = {} for n in names: if n != '': vNames[n] = [] features = Grid.selectedFeatures() if len(features) == 0: features = Grid.getFeatures() total = Grid.featureCount() else: total = len(features) total = 100.0/total for enum,feature in enumerate(features): if total != -1: feedback.setProgress(int(enum*total)) for name in vNames.keys(): try: v = feature[name] if type(v) == PyQt5.QtCore.QDateTime: v = v.toPyDateTime().strftime('%d/%m/%Y, %H:%M:%S') vNames[name].append(v) except Exception: vNames[name].append(0) continue df = pd.DataFrame(vNames) if S == '': df['Size'] = 10 S = 'Size' if G == '': df['Trace'] = '1' G = 'Trace' df[G] = df[G].astype(str) if A: df.sort_values(by=[T], inplace=True) if Y: if Z: fig = px.scatter_ternary(df, a=X, b=Y, c=Z, animation_frame=T, color=G,size=S) else: xRange = [df[X].min()*0.9,df[X].max()*1.1] yRange = [df[Y].min()*0.9,df[Y].max()*1.1] fig = px.scatter(df, x=X, y=Y, animation_frame=T, color=G,size=S,range_x=xRange,range_y=yRange) else: if G == '': fig = px.histogram(df, x=X, animation_frame=T) else: fig = px.histogram(df, x=X, animation_frame=T, color=G) fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = speed else: if T != '': df.sort_values(by=[T], inplace=True) if Y: if Z: fig = px.scatter_ternary(df, a=X, b=Y, c=Z, color=G,size=S) else: xRange = [df[X].min()*0.9,df[X].max()*1.1] yRange = [df[Y].min()*0.9,df[Y].max()*1.1] if T == '': fig = px.scatter(df, x=X, y=Y, color=G,size=S,range_x=xRange,range_y=yRange) else: fig = px.line(df, x=X, y=Y, color=G,range_x=xRange,range_y=yRange) else: if G == '': fig = px.histogram(df, x=X) else: fig = px.histogram(df, x=X, color=G) try: py.plot(fig, filename='Animation', auto_open=True) except Exception as e: fig.show() return {}
import plotly.express as px df = { 'Информатика': [3.3, 4.4, 3.5, 5, 2], 'Физика': [3.2, 4.5, 5, 5, 5], 'Математика': [3.4, 3.8, 4.2, 2, 5] } fig = px.scatter_ternary(df, a="Информатика", b="Физика", c="Математика", color="Математика", size="Математика", hover_name="Математика", size_max=20, template='presentation') fig.show()
IO_Path( empirical_path.format(*col_set), postpred_path.format(*col_set), out_path.format(*col_set), { 'a': 'C_{}'.format(col_set[0]), 'b': 'C_{}'.format(col_set[1]), 'c': 'C_{}'.format(col_set[2]) }, )) for path in paths: emp = pd.DataFrame(polar_to_simplex(pd.read_csv(path.emp).values), columns=[path.colnames[x] for x in ['a', 'b', 'c']]) emp['source'] = 'Empirical' pp = pd.DataFrame(polar_to_simplex(pd.read_csv(path.pp).values), columns=[path.colnames[x] for x in ['a', 'b', 'c']]) pp['source'] = 'PostPred' selected_rows = sample(range(pp.shape[0]), emp.shape[0]) out_df = pd.concat([emp, pp.iloc[selected_rows, ]], axis=0) fig = px.scatter_ternary(out_df, color='source', **path.colnames) fig.write_image(path.out) del (fig) del (emp) del (pp) # EOF
df_wind = px.data.wind() px.line_polar(df_wind, r= 'frequency',theta = 'direction',color='strength',line_close=True,template="plotly_dark") # In[85]: #ternary plot # In[87]: df_exp = px.data.experiment() px.scatter_ternary(df_exp, a='experiment_1',b ='experiment_2',c='experiment_3',hover_name='group',color="gender") # In[88]: #facets # In[91]: df_tips = px.data.tips() px.scatter(df_tips,x='total_bill',y='tip',color='smoker',facet_col='sex') px.histogram(df_tips,x = 'total_bill', y ='tip',color='sex',facet_row='time',facet_col='day',category_orders={'day':["Thur","fri","Sat","Sun"],"time":["Lunch","Dinner"]})
figthhhh = px.scatter(dmtrial, x="Hour", y="Comments", color= 'Hour', size='Upvotes', hover_name = "Title", title="Number of comments on r/Ask Subreddits with Time of Day, with Size of Dots indicating Upvotes") figthhhh.show() figthhhh.write_html("Fig13.html") #fig321 = px.scatter(dmhours, x="Hour", y="Upvotes", color= 'Upvote Ratio', title="//") #fig321.show() figtt = px.scatter_ternary(dmhours, a = 'Downvotes', b = 'Comments', c = 'Upvotes', hover_name = 'Title', color = 'Upvote Ratio', title="Ternary Plot of Relative Upvotes, Downvotes, and Comments on r/Ask Subreddits") figtt.show() figtt.write_html("Fig14.html") #figtta = px.scatter_ternary(dmhours, a = 'Upvotes', b = 'Comments', c = 'Comment/Upvote Ratio') #figtta.show()
def ternary(df): import numpy as np features = df.columns.to_list() clean_features = [] for name in features: if df[name].dtypes == np.float or df[name].dtypes == np.int64: clean_features.append(name) fig = px.scatter_ternary(df, a=clean_features[2], b=clean_features[3], c=clean_features[4], size_max=15, color=df['MINERAL PREDICTED']) return html.Div([ html.Div([ dcc.Dropdown(id='dropdown1', options=[{ 'label': i, 'value': i } for i in clean_features], value=clean_features[2]) ], style={ 'width': '24%', 'display': 'inline-block' }), html.Div([ dcc.Dropdown(id='dropdown2', options=[{ 'label': i, 'value': i } for i in clean_features], value=clean_features[3]) ], style={ 'width': '24%', 'display': 'inline-block' }), html.Div([ dcc.Dropdown(id='dropdown3', options=[{ 'label': i, 'value': i } for i in clean_features], value=clean_features[4]) ], style={ 'width': '24%', 'display': 'inline-block' }), html.Div([ dcc.Dropdown(id='dropdown4', options=[{ 'label': 'MINERAL PREDICTED', 'value': 'MINERAL PREDICTED' }, { 'label': 'GROUP PREDICTED', 'value': 'GROUP PREDICTED' }], value='MINERAL PREDICTED') ], style={ 'width': '24%', 'display': 'inline-block' }), html.Div(id='dd-output-container'), dcc.Graph(id='ternary-graph', figure=fig) ], style={'passing': 10})
import plotly.graph_objects as go import plotly.express as px import statsmodels.api as sm df = pd.read_csv('/Users/william/Desktop/Python Website/output4.csv') fig = px.scatter_ternary( df, a="Relative Upvotes", b="Relative Comments", c="Relative Downvotes", hover_name="Title", opacity=0.7, color="Topic", size="Upvotes", size_max=9, title= 'Post reception within news Subreddits by category (2020) — Normalized Upvotes, Comments, and Downvotes', color_discrete_map={ "Donald Trump": "darkred", "Joe Biden": "blue", "Racial Justice Protests": "orange", "COVID-19": "black", "The Economy": "green" }) '''trace_a = go.Scatterternary({ 'mode': 'markers', 'name': 'Donald Trump', 'a': df.loc[df['Topic'] == 'Donald Trump']['Relative Upvotes'], 'b': df.loc[df['Topic'] == 'Donald Trump']['Relative Comments'], 'c': df.loc[df['Topic'] == 'Donald Trump']['Relative Downvotes'],
def generate_ternary(data, x, y, z, data_format="long", **kwargs): if data_format == "long": return px.scatter_ternary(data, a=x[0], b=y[0], c=z[0], **kwargs)