本文整理汇总了Python中plotly.tools.FigureFactory类的典型用法代码示例。如果您正苦于以下问题:Python FigureFactory类的具体用法?Python FigureFactory怎么用?Python FigureFactory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FigureFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: slack_stock_price
def slack_stock_price(msg: CommandMessage, config: Dict):
if len(msg.text) > 1:
try:
response = BarchartClient(config.get('api_key', '')) \
.get_history(msg.text.upper())
except:
# API request error
# Already logged in BarchartClient, so just return error message.
return "Something went wrong with %s" % msg.text
else:
try:
open_prices = []
high_prices = []
low_prices = []
close_prices = []
dates = []
volumes = []
for result in response['results']:
open_prices.append(result['open'])
high_prices.append(result['high'])
low_prices.append(result['low'])
close_prices.append(result['close'])
dates.append(result['tradingDay'])
volumes.append(result['volume'])
candle_graph_url = plotly.plot(
FigureFactory.create_candlestick(open_prices,
high_prices,
low_prices,
close_prices,
dates=dates),
filename="barchart/price_" + dates[-1],
vadlidate=False)
volume_graph_url = plotly.plot(
Data([Scatter(x=dates,
y=volumes)]))
attachments = [
MessageAttachment(fallback="stock price history",
title="stock price history",
title_link=candle_graph_url,
image_url=candle_graph_url + ".png"),
MessageAttachment(fallback="volume history",
title="volume history",
title_link=volume_graph_url,
image_url=volume_graph_url + ".png")]
return SlackMessage(
text="Stock price history for %s" % msg.text,
attachments=attachments)
except Exception as e:
# Response handling error
logging.error(e)
return "Something went wrong with %s" % msg.text
else:
return "Please enter ticker symbol."
示例2: make_plotly_figs
def make_plotly_figs():
from plotly.tools import FigureFactory as FF
import numpy as np
x1 = np.random.randn(200)
hist_data = [x1]
group_labels = ['Group 1']
# Create distplot with curve_type set to 'normal'
fig = FF.create_distplot(hist_data, group_labels, bin_size=.25, show_curve=False)
# Add title
fig['layout'].update(title='Plot')
return [fig]
示例3: dist_plot
def dist_plot(df,
groupby=None,
val=None,
bin_size=1,
title=None,
show_hist=True,
show_kde=True,
show_rug=True,
show_legend=True,
figsize=None,
outfile=None,
xlabel=None,
ylabel=None):
if groupby is None:
fig = FF.create_distplot([df[c] for c in df.columns],
df.columns.values.tolist(),
bin_size=bin_size,
show_rug=show_rug,
show_curve=show_kde)
else:
groups = sorted(df[groupby].unique().tolist(), reverse=True)
data = []
if val is None:
val = df.columns.drop(groupby)[0] # choose first non-groupby column
for group in groups:
mask = df[groupby] == group
data.append(df.loc[mask, val])
fig = FF.create_distplot(data,
groups,
bin_size=bin_size,
show_hist=show_hist,
show_rug=show_rug,
show_curve=show_kde)
fig['layout'].update(showlegend=show_legend)
if title:
fig['layout'].update(title=title)
if xlabel:
fig['layout'].update(xaxis=go.XAxis(title=xlabel))
if ylabel:
fig['layout'].update(yaxis=go.YAxis(title=ylabel))
if figsize and len(figsize) == 2:
fig['layout'].update(width=figsize[0])
fig['layout'].update(height=figsize[1])
ol.iplot(fig, show_link=False)
# write figure to HTML file
if outfile:
print('Exporting copy of figure to %s...' % outfile)
ol.plot(fig, auto_open=False, filename=outfile)
示例4: pretty_table
def pretty_table(df, outfile=None):
"""
Display pandas dataframe as a nicely-formated HTML
Parameters
----------
outfile: filepath str
If provided, output to an HTML file at provided location
Example
-------
import pandas as pd
animals = pd.DataFrame([
['cat',10, 'housepet'],
['dog',20,'housepet'],
['fish',5,'housepet'],
['cat',20,'zooanimal'],
['dog',50,'zooanimal'],
['fish',20,'zooanimal'],], columns=['animal','value','group'])
pretty_table(animals)
"""
table = FF.create_table(df)
ol.iplot(table, show_link=False)
# write figure to HTML file
if outfile:
print('Exporting copy of figure to %s...' % outfile)
ol.plot(table, auto_open=False, filename=outfile)
示例5: scatter_matrix
def scatter_matrix(self, dataframe, select_columns=None, index_colname=None,
diag_kind='scatter',
marker_size=10, height=800, width=1000, marker_outline_width=0,
marker_outline_color='black'):
"""
Create a scatter matrix plot from dataframes using Plotly.
Args:
dataframe: (array) array of the data with column headers
select_columns: (list) names/headers of columns to plot from the dataframe
index_colname: (str) name of the index column in data array
diag_kind: (str) sets the chart type for the main diagonal plots (default='scatter')
Choose from 'scatter'/'box'/'histogram'
marker_size: (float) sets the marker size (in px)
height: (int/float) sets the height of the chart
width: (int/float) sets the width of the chart
marker_outline_width: (int) thickness of marker outline (currently affects the outline of histograms too
when "diag_kind" = 'histogram')
marker_outline_color: (str/array) color of marker outline - accepts similar formats as other color variables
Returns: a Plotly scatter matrix plot
"""
df = dataframe[select_columns] if select_columns else dataframe
fig = FF.create_scatterplotmatrix(df, index=index_colname, diag=diag_kind, size=marker_size,
height=height, width=width)
# Add outline to markers
for trace in fig['data']:
trace['marker']['line'] = dict(width=marker_outline_width, color=marker_outline_color)
self.create_plot(fig)
示例6: add_surface
def add_surface(self, xyz, triangles, lighting=None, **kwargs):
"""Add a surface model to the plotly figure.
xyz : array, shape (n_vertices, 3)
An xyz array defining the position of each vertex in 3-D
triangles : array, shape (n_triangles, 3)
An ijk array defining triangles for the mesh. Each row
indexes 3 rows of in xyz, which together make a triangle.
lighting : None | dict
A dictionary specifying lighting parameters in plotly
"""
if lighting is None:
lighting = dict(ambient=.4, specular=1)
self.xyz = xyz
self.x = xyz.T[0]
self.y = xyz.T[1]
self.z = xyz.T[2]
self.triangles = triangles
self.xrange = np.array([xyz.min(0)[0], xyz.max(0)[0]])
self.yrange = np.array([xyz.min(0)[1], xyz.max(0)[1]])
self.zrange = np.array([xyz.min(0)[2], xyz.max(0)[2]])
colors = self.cmap(np.repeat(.5, len(triangles)))
colors = array_to_plotly(colors)
self.surfacedata = ff._trisurf(
x=self.x, y=self.y, z=self.z, simplices=self.triangles,
color_func=colors, **kwargs)
self.surfacedata[0]['lighting'] = lighting
self.facecolors = self.surfacedata[0]['facecolor'].copy()
self.tri_centroids = xyz[triangles].mean(1)
self.layout['scene'].update(dict(xaxis=dict(range=self.xrange),
yaxis=dict(range=self.yrange),
zaxis=dict(range=self.zrange)))
示例7: plot_Age
def plot_Age(path, feature, type_):
feature = pd.DataFrame(feature)
feature = feature.reset_index()
data = folder_reader(path)
data.columns = ['temperature', 'wind', 'age', 'total']
aux = data[data.age < 1950]
aux = aux.groupby(type_)['total'].sum()
aux = aux.reset_index()
aux = pd.merge(aux, feature, how='left', left_index=type_, right_index="index")
number = aux[aux.columns[1]] * 100 / aux[aux.columns[3]]
Temp_1 = np.repeat(aux[aux.columns[0]].values, number.round(0).astype(int))
aux = data[data.age >= 1950]
aux = aux[aux.age < 1985]
aux = aux.groupby(type_)['total'].sum()
aux = aux.reset_index()
aux = pd.merge(aux, feature, how='left', left_index=type_, right_index="index")
number = aux[aux.columns[1]] * 100 / aux[aux.columns[3]]
Temp_2 = np.repeat(aux[aux.columns[0]].values, number.round(0).astype(int))
aux = data[data.age >= 1985]
aux = aux.groupby(type_)['total'].sum()
aux = aux.reset_index()
aux = pd.merge(aux, feature, how='left', left_index="wind", right_index="index")
number = aux[aux.columns[1]] * 100 / aux[aux.columns[3]]
Temp_3 = np.repeat(aux[aux.columns[0]].values, number.round(0).astype(int))
hist_data = [Temp_1, Temp_2, Temp_3]
group_labels = ['Older than 65', 'Betwen 30-65', 'Younger than 30']
colors = ['rgb(0, 0, 100)', 'rgb(0, 200, 200)', 'rgb(0, 300, 300)']
fig = FF.create_distplot(hist_data, group_labels, colors=colors)
plot_url = py.offline.plot(fig)
示例8: main
def main(stock_name, day_in, future):
"""Control DataBase and make graph if have stock_name"""
year, month, day = 2015, 12, 12
open_data, close_data, high_data, low_data, values_data, dates = [], [], [], [], [], []
while day_in > 0:
file_name = "set-history_EOD_" + "%d-%02d-%02d.csv" % step_day(year, month, day)
try:
temporary = csv.reader(open(file_name, "r"))
bug = 1
for row in temporary:
if row[0] == stock_name:
bug = 0
open_data.append(float(row[2]))
high_data.append(float(row[3]))
low_data.append(float(row[4]))
close_data.append(float(row[5]))
values_data.append(float(row[6]) * float(row[5]))
dates.append(datetime(year=int(row[1][0:4]), month=int(row[1][4:6]), day=int(row[1][6:])))
if bug == 1:
it_bug ## Make error when that day haven't stock_name
day_in -= 1
except:
day_in -= 1 ## Count All day with have stock or no for can find graph of year from 365 day
year, month, day = step_day(year, month, day)
open_data, close_data, high_data, low_data, values_data, dates = (
open_data[::-1],
close_data[::-1],
high_data[::-1],
low_data[::-1],
values_data[::-1],
dates[::-1],
)
if len(open_data) == 0:
return "%s not found" % stock_name
data_sma, date_sma = make_sma(future, close_data, dates)
data_ema15, date_ema15 = make_ema(15, close_data, dates)
data_ema50, date_ema50 = make_ema(50, close_data, dates)
add_sma = Scatter(x=date_sma, y=data_sma, name="SMA%d" % (future), line=Line(color="rgb(166,212,64)"))
add_ema15 = Scatter(x=date_ema15, y=data_ema15, name="EMA15", line=Line(color="purple"))
add_ema50 = Scatter(x=date_ema50, y=data_ema50, name="EMA50", line=Line(color="blue"))
add_high = Scatter(x=dates, y=[max(high_data) for i in range(len(dates))], name="HIGH", line=Line(color="black"))
add_low = Scatter(x=dates, y=[min(low_data) for i in range(len(dates))], name="LOW", line=Line(color="black"))
fig = FF.create_candlestick(open_data, high_data, low_data, close_data, dates=dates)
fig["layout"].update({"title": stock_name, "yaxis": {"title": "Price"}, "xaxis": {"title": "Dates"}})
fig["data"].extend([add_high])
fig["data"].extend([add_low])
fig["data"].extend([add_sma])
fig["data"].extend([add_ema15])
fig["data"].extend([add_ema50])
plot_url = py.plot(fig, filename="candlestick", validate=False)
data = [go.Bar(x=dates, y=values_data)]
layout = go.Layout(title="Values of %s" % stock_name)
fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename="text-hover-bar")
return "Graph %s Success" % stock_name
示例9: financialplots
def financialplots(filename, plotkind):
try:
data = pd.read_csv(filename,index_col=0, parse_dates=True)
except(FileNotFoundError, IOError):
print('Wrong file or file path.')
return None
if plotkind == 'candlestick':
fig = FF.create_candlestick(data['Opening Price'], data['Maximum Price'], data['Minimum Price'], data['Closing Price'],dates=data.index)
elif plotkind == 'macd':
fig = data['Closing Price'].ta_plot(study='macd', fast_period=12, slow_period=26, signal_period=9, asFigure=True)
elif plotkind == 'boll':
fig = data['Closing Price'].ta_plot(study='boll',asFigure=True)
elif plotkind == 'ohlc':
fig = FF.create_ohlc(data['Opening Price'], data['Maximum Price'], data['Minimum Price'], data['Closing Price'],dates=data.index)
elif plotkind == 'sma':
fig = data['Closing Price'].ta_plot(study='sma', asFigure=True)
py.plot(fig,filename='../../plots/'+filename[:-4]+plotkind,validate=False,auto_open=False)
示例10: plot_tables
def plot_tables():
data_matrix_dem = [
['Feature', 'Coeff', 'Std Err', 'P Val'],
['State Average Turnout', 0.0048, 0.000, 0.000],
['Rural-urban Continuum Code', 0.0046, 0.000, 0.000],
['Perc Less than Highschool Diploma', 0.0006, 0.000, 0.000],
['Perc with Bachelor\'s', 0.0032, 8.54e-05, 0.000],
['Unemployment Rate', 0.0041, 0.000, 0.000],
['Religion NMF Feature 1', 0.0091, 0.001, 0.000],
['Religion NMF Feature 2', 0.0063, 0.000, 0.000],
['Campaign Expenditure', -4.084e-10, 5.09e-11, 0.000],
['Cook Index', 0.4752, 0.006, 0.000],
['Change in Vote Share 2008->2012', 0.2689, 0.024, 0.000],
['1 Field Office', 0.0088, 0.002, 0.000],
['2+ Field Offices', 0.0257, 0.004, 0.000],
['Field Office - Cook Index Interaction', 0.0348, 0.017, 0.041]
]
data_matrix_rep =[
['Feature', 'Coeff', 'Std Err', 'P Val'],
['State Average Turnout', 0.0060, 0.000, 0.000],
['Rural-urban Continuum Code', 0.0044, 0.000, 0.000],
['Perc Less than Highschool Diploma', -0.0024, 0.000, 0.000],
['Perc with Bachelor\'s', 0.0025, 0.000, 0.000],
['Unemployment Rate', 0.0054, 0.000, 0.000],
['Religion NMF Feature 1', 0.0003, 0.001, 0.700],
['Religion NMF Feature 2', 0.0072, 0.001, 0.000],
['Campaign Expenditure', -4.905e-10, 6.44e-11, 0.000],
['Cook Index', -0.5827, 0.008, 0.000],
['Change in Vote Share 2008->2012', -0.0543, 0.032, 0.000],
['1 Field Office', 0.0087, 0.004, 0.025],
['2+ Field Offices', 0.0143, 0.008, 0.080],
['Field Office - Cook Index Interaction', -.1054, 0.029, 0.000]
]
table_dem = FF.create_table(data_matrix_dem)
table_dem.layout.update({'title': 'Democratic Regression<br><i>Adj R2 0.978<i>'})
table_rep = FF.create_table(data_matrix_rep)
table_rep.layout.update({'title': 'Republican Regression<br><i>Adj R2 0.982<i>'})
# fig = tools.make_subplots(rows=1, cols=2, subplot_titles=('Democratic Regression<br><i>Adj R2 0.978<i>',
# 'Republican Regression<br><i>Adj R2 0.982<i>'))
plot_url = py.plot(table_dem, filename='Dem Regression Results')
plot_url = py.plot(table_rep, filename='Rep Regression Results')
示例11: build_plotly_table
def build_plotly_table(plotly_df):
plotly_df = plotly_df[['Passer_Name', 'Receiver_Name', 'Assists']]
plotly_df = plotly_df.sort_values(by='Assists', ascending=False)
plotly_df = plotly_df.head(25)
plotly_df.columns = ['Passer', 'Receiver', 'Assists']
plotly_df = plotly_df.as_matrix()
plotly_df = np.insert(plotly_df, 0, np.array(('Passer', 'Receiver', 'Assists')), 0)
table = FF.create_table(plotly_df)
py.iplot(table, filename='assist_pairs')
示例12: make_candlestick
def make_candlestick(gamelog, column, reduce_func=None):
base_series = gamelog.set_index("Date")[column]
if reduce_func:
series = reduce_func(base_series).dropna()
else:
series = base_series.cumsum().dropna()
weekdata = list(create_weekly(series))
weeks = pd.DataFrame(weekdata).dropna()
fig = FF.create_candlestick(weeks.Open, weeks.High, weeks.Low, weeks.Close,
dates=weeks.start_date)
fig['layout'].update(height=600, width=600, title=column)
return fig
示例13: search
def search(self, data_rows, key):
data = data_rows[0]
if key == 'searchUser':
data_matrix = [['Username', 'Count'],
[data[0], data[1]]]
elif key == 'searchSubred':
data_matrix = [['Subreddit', 'Count'],
[data[0], data[1]]]
colorscale = [[0, '#4d004c'], [.5, '#ffffff'], [1, '#f2e5ff']]
table = FF.create_table(data_matrix, colorscale=colorscale)
plotted = plotly.offline.plot(table, filename='../graphs.html')
return plotted
示例14: scatter_matrix
def scatter_matrix(self, dataframe, select_columns=None, index_colname=None, diag_kind='scatter',
marker_size=10, height=800, width=1000, marker_outline_width=0, marker_outline_color='black'):
"""
Create a scatter matrix plot from dataframes using Plotly.
Args:
dataframe: (array) array of the data with column headers
select_columns: (list) names/headers of columns to plot from the dataframe
index_colname: (str) name of the index column in data array
diag_kind: (str) sets the chart type for the main diagonal plots (default='scatter')
Choose from 'scatter'/'box'/'histogram'
marker_size: (float) sets the marker size (in px)
height: (int/float) sets the height of the chart
width: (int/float) sets the width of the chart
marker_outline_width: (int) thickness of marker outline (currently affects the outline of histograms too
when "diag_kind" = 'histogram')
marker_outline_color: (str/array) color of marker outline - accepts similar formats as other color variables
Returns: a Plotly scatter matrix plot
"""
df = dataframe[select_columns] if select_columns else dataframe
fig = FF.create_scatterplotmatrix(df, index=index_colname, diag=diag_kind, size=marker_size,
height=height, width=width)
# Add outline to markers
for trace in fig['data']:
trace['marker']['line'] = dict(width=marker_outline_width, color=marker_outline_color)
if self.plot_mode == 'offline':
if self.filename:
plotly.offline.plot(fig, filename=self.filename)
else:
plotly.offline.plot(fig)
elif self.plot_mode == 'notebook':
plotly.offline.init_notebook_mode() # run at the start of every notebook; version 1.9.4 required
plotly.offline.iplot(fig)
elif self.plot_mode == 'online':
plotly.tools.set_credentials_file(username=self.username, api_key=self.api_key)
if self.filename:
plotly.plotly.plot(fig, filename=self.filename, sharing='public')
else:
plotly.plotly.plot(fig, sharing='public')
elif self.plot_mode == 'static':
plotly.plotly.image.save_as(fig, filename=self.filename, height=self.height, width=self.width,
scale=self.scale)
示例15: readAssetReturnsCSV
def readAssetReturnsCSV(asset):
df = pandas.read_csv('../../Daily/' + asset + '.csv')
df['Index'] = pandas.to_datetime(df['Index']) # convert dates to Datetime objects
df = df.set_index('Index') # set Index
df = df.sort_index() # sort by date
# Will store the weekly data
df_calcs = pandas.DataFrame(columns=['period_ended', 'open', 'high', 'low', 'close', 'volume',
'adj.', 'weekly_return'])
# compute weekly returns only across full trading weeks (Monday -> Friday)
for index, row in df.iterrows():
date = pandas.to_datetime(index)
if date.weekday() == 4: # is Friday
thur = date + datetime.timedelta(days=-1)
wed = date + datetime.timedelta(days=-2)
tues = date + datetime.timedelta(days=-3)
mon = date + datetime.timedelta(days=-4)
# trading occurred on corresponding Friday
if thur in df.index and wed in df.index and tues in df.index and mon in df.index:
period_ended = date
open = df.loc[mon]['open']
close = row['close']
low = min(df.loc[mon]['low'], df.loc[tues]['low'], df.loc[wed]['low'], df.loc[thur]['low'],
row['close'])
high = max(df.loc[mon]['high'], df.loc[tues]['high'], df.loc[wed]['high'], df.loc[thur]['high'],
row['high'])
volume = df.loc[mon]['volume'] + df.loc[tues]['volume'] + df.loc[wed]['volume'] + \
df.loc[thur]['volume'] + row['volume']
adj = row['adj.']
weekly_return = (row['adj.'] - df.loc[mon]['adj.']) / df.loc[mon]['adj.']
#print(mon, '(', df.loc[mon]['adj.'], ') ->', date, '(', row['adj.'], '):', weekly_return*100, '%')
week = pandas.Series([period_ended, open, high, low, close, volume, adj, weekly_return])
week = week.rename({0: 'period_ended', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume',
6: 'adj.', 7: 'weekly_return'})
df_calcs = df_calcs.append(week, ignore_index=True)
df_calcs = df_calcs.set_index('period_ended') # set index to period_ended
# standardize weekly returns
df_calcs['std_return'] = (df_calcs['weekly_return'] - df_calcs['weekly_return'].mean()) / \
df_calcs['weekly_return'].std()
# save OHLC data
ohlc = FF.create_ohlc(df_calcs.open, df_calcs.high, df_calcs.low, df_calcs.close, dates=df_calcs.index)
return Asset.Asset(asset, df_calcs, ohlc)