本文整理汇总了Python中plotly.graph_objs.Heatmap方法的典型用法代码示例。如果您正苦于以下问题:Python graph_objs.Heatmap方法的具体用法?Python graph_objs.Heatmap怎么用?Python graph_objs.Heatmap使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类plotly.graph_objs
的用法示例。
在下文中一共展示了graph_objs.Heatmap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_query
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def run_query(ont, aset, args):
"""
Basic querying by positive/negative class lists
"""
subjects = aset.query(args.query, args.negative)
for s in subjects:
print("{} {}".format(s, str(aset.label(s))))
if args.plot:
import plotly.plotly as py
import plotly.graph_objs as go
tups = aset.query_associations(subjects=subjects)
z, xaxis, yaxis = tuple_to_matrix(tups)
spacechar = " "
xaxis = mk_axis(xaxis, aset, args, spacechar=" ")
yaxis = mk_axis(yaxis, aset, args, spacechar=" ")
logging.info("PLOTTING: {} x {} = {}".format(xaxis, yaxis, z))
trace = go.Heatmap(z=z,
x=xaxis,
y=yaxis)
data=[trace]
py.plot(data, filename='labelled-heatmap')
示例2: run_query_associations
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def run_query_associations(ont, aset, args):
if args.dendrogram:
plot_subject_term_matrix(ont, aset, args)
return
import plotly.plotly as py
import plotly.graph_objs as go
tups = aset.query_associations(subjects=args.subjects)
for (s,c) in tups:
print("{} {}".format(s, c))
z, xaxis, yaxis = tuple_to_matrix(tups)
xaxis = mk_axis(xaxis, aset, args)
yaxis = mk_axis(yaxis, aset, args)
logging.info("PLOTTING: {} x {} = {}".format(xaxis, yaxis, z))
trace = go.Heatmap(z=z,
x=xaxis,
y=yaxis)
data=[trace]
py.plot(data, filename='labelled-heatmap')
#plot_dendrogram(z, xaxis, yaxis)
# TODO: fix this really dumb implementation
示例3: csv_heatmap_generator_plotly
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def csv_heatmap_generator_plotly(in_directory, output_directory, output_file_name):
"""
Plots heatmaps for all the csv files in the given directory
Args:
in_directory (str): location of input csv files
output_drectory(str): location to save graph
output_file_name(str): name of the image file to be saved
Returns:
null
"""
file_list = glob.glob(in_directory+"*.csv")
for file in file_list:
csv_data = genfromtxt(file, delimiter=',')
trace = go.Heatmap(
z=csv_data,
x=list(range(48)),
y=list(range(1, 12)),
colorscale=[
[0, 'rgb(255, 255, 204)'],
[0.13, 'rgb(255, 237, 160)'],
[0.25, 'rgb(254, 217, 118)'],
[0.38, 'rgb(254, 178, 76)'],
[0.5, 'rgb(253, 141, 60)'],
[0.63, 'rgb(252, 78, 42)'],
[0.75, 'rgb(227, 26, 28)'],
[0.88, 'rgb(189, 0, 38)'],
[1.0, 'rgb(128, 0, 38)']
]
)
data = [trace]
layout = go.Layout(title='HeatMap', width=800, height=640)
fig = go.Figure(data=data, layout=layout)
py.image.save_as(fig, filename=in_directory+file[file.rfind("/")+1:-4]+'_heatmap.png')
示例4: test_csv_heatmap_generator_plotly
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def test_csv_heatmap_generator_plotly(self, mock_py):
test_data = np.array([[5075, 507, 634, 7237, 3421, 7522, 12180, 9635, 7381, 7967, 6224, 2712, 4758, 2704, 1763,
1869, 4428, 1680],
[1652, 425, 269, 982, 2687, 15318, 3865, 3213, 4411, 6821, 1960, 7007, 883, 4592, 0, 3271,
619, 1508],
[1578, 924, 409, 1115, 6088, 491, 1923, 10700, 16206, 8690, 1350, 3778, 237, 1095, 20639,
2669, 1956, 6015]])
trace = go.Heatmap(
z=test_data,
x=list(range(48)),
y=list(range(1, 12)),
colorscale=[
[0, 'rgb(255, 255, 204)'],
[0.13, 'rgb(255, 237, 160)'],
[0.25, 'rgb(254, 217, 118)'],
[0.38, 'rgb(254, 178, 76)'],
[0.5, 'rgb(253, 141, 60)'],
[0.63, 'rgb(252, 78, 42)'],
[0.75, 'rgb(227, 26, 28)'],
[0.88, 'rgb(189, 0, 38)'],
[1.0, 'rgb(128, 0, 38)']
]
)
final_data = [trace]
layout = go.Layout(title='HeatMap', width=800, height=640)
fig = go.Figure(data=final_data, layout=layout)
vis.csv_heatmap_generator_plotly(self.test_data_dir + "/vis/", self.test_data_dir, "plotly_heatmap_test")
self.assertEqual(mock_py.call_count, 1)
self.assertTrue(fig.get('layout') == mock_py.call_args[0][0].get('layout'))
np.testing.assert_array_equal(fig.data[0].get('z'), mock_py.call_args[0][0].data[0].get('z'))
示例5: plot_intersections
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def plot_intersections(ont, aset, args):
import plotly.plotly as py
import plotly.graph_objs as go
(z, xaxis, yaxis) = create_intersection_matrix(ont, aset, args)
trace = go.Heatmap(z=z,
x=xaxis,
y=yaxis)
data=[trace]
py.plot(data, filename='labelled-heatmap')
示例6: fig_heatmap
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def fig_heatmap(df_matrix, title=""):
"""Generate heatmap figure from NxN matrix.
Args:
df_matrix (pandas.DataFrame): Matrix as DataFrame. Index values and column values must be equal.
title (str): Title of plot. Defaults to "".
Returns:
plotly.graph_objs.Figure
"""
trace = go.Heatmap(
z=df_matrix,
x=df_matrix.columns,
y=df_matrix.index,
hovertemplate='%{y} ---> %{x}<extra>%{z}</extra>',
colorscale='Greens'
)
data = [trace]
layout = {
'title': {'text': title},
'xaxis': {'title': "Receiver"},
'yaxis': {'title': "Sender"}
}
fig = go.Figure(data=data, layout=layout)
return fig
示例7: get_figure
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def get_figure(self):
from pandas import MultiIndex
layout = dict(legend=dict(x=0.7, y=1), margin=dict(r=0, t=40))
is_3d = isinstance(self.table.index, MultiIndex)
if is_3d:
import plotly.graph_objs as go
from plotly import tools
cols = self.table.columns
ncols = 2 if len(cols) > 1 else 1
nrows = len(cols) / ncols + len(cols) % ncols
fig = tools.make_subplots(
rows=nrows, cols=ncols, subplot_titles=cols, print_grid=False
)
for idx, col in enumerate(cols):
series = self.table[col]
z = [s.tolist() for _, s in series.groupby(level=0)]
fig.append_trace(
go.Heatmap(z=z, showscale=False), idx / ncols + 1, idx % ncols + 1
)
fig["layout"].update(layout)
else:
xaxis = self.config.get("x", self.table.columns[0])
yaxis = self.config.get("y", None)
yaxes = (
[yaxis]
if yaxis is not None
else [col for col in self.table.columns if col != xaxis]
)
traces = []
for axis in yaxes:
if "ₑᵣᵣ" not in axis:
tbl = self.table[[xaxis, axis]].replace("", np.nan).dropna()
traces.append(
dict(x=tbl[xaxis].tolist(), y=tbl[axis].tolist(), name=axis)
)
for trace in traces:
err_axis = trace["name"] + "ₑᵣᵣ"
if err_axis in yaxes:
errors = self.table[err_axis].replace("", np.nan).dropna()
trace["error_y"] = dict(type="data", array=errors, visible=True)
trace["mode"] = "markers"
layout.update(
dict(
xaxis=dict(title=xaxis),
yaxis=dict(
title=self.config.get("ytitle"),
type=self.config.get("yaxis", {}).get("type", "-"),
),
showlegend=self.config.get("showlegend", True),
)
)
fig = dict(data=traces, layout=layout)
return fig
示例8: plot_synergies
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def plot_synergies():
synergies = np.loadtxt('pretrained/synergies_all.csv')
for i in range(114):
synergies[i, i] = 0.5
hero_dict = get_hero_dict()
x_labels = []
for i in range(114):
if i != 23:
x_labels.append(hero_dict[i + 1])
synergies = np.delete(synergies, [23], 0)
synergies = np.delete(synergies, [23], 1)
trace = go.Heatmap(z=synergies,
x=x_labels,
y=x_labels,
colorscale='Viridis')
layout = go.Layout(
title='Hero synergies',
width=1000,
height=1000,
xaxis=dict(ticks='',
nticks=114,
tickfont=dict(
size=8,
color='black')),
yaxis=dict(ticks='',
nticks=114,
tickfont=dict(
size=8,
color='black'))
)
data = [trace]
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='heatmap_synergies')
示例9: plot_counters
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def plot_counters():
counters = np.loadtxt('pretrained/counters_all.csv')
for i in range(114):
counters[i, i] = 0.5
hero_dict = get_hero_dict()
x_labels = []
for i in range(114):
if i != 23:
x_labels.append(hero_dict[i + 1])
counters = np.delete(counters, [23], 0)
counters = np.delete(counters, [23], 1)
trace = go.Heatmap(z=counters,
x=x_labels,
y=x_labels,
colorscale='Viridis')
layout = go.Layout(
title='Hero counters (hero1 winrate against hero2)',
width=1000,
height=1000,
xaxis=dict(ticks='',
nticks=114,
title='hero2',
tickfont=dict(
size=8,
color='black')),
yaxis=dict(ticks='',
nticks=114,
title='hero1',
tickfont=dict(
size=8,
color='black'))
)
data = [trace]
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='heatmap_counters')
示例10: make_calendar_heatmap_fig
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def make_calendar_heatmap_fig(n, start_date, end_date):
start_date = arrow.get(start_date)
end_date = arrow.get(end_date)
categories = ["BAT", "Diary", "Exercise"]
dates = []
z = []
for _ in categories:
z.append([])
for r in arrow.Arrow.range("day", start_date, end_date):
offset_day = (arrow.now() - r).days
record_data = data_handler.read_record(days=-offset_day)
summary = record_data.get("summary", {})
for i, category in enumerate(categories):
do_category = summary.get(f"do_{category.lower()}", False)
z[i].append(int(do_category))
dates.append(r.format("YYYY-MM-DD"))
categories.append("All")
z_do_all = []
for i in range(len(dates)):
do_all = 0
for item in z:
do_all += item[i]
z_do_all.append(do_all)
z.append(z_do_all)
fig = go.Figure(
data=go.Heatmap(
z=z,
text=z,
x=dates,
y=categories,
colorscale=[[0, "#FFFFFF"], [1, "#19410a"]],
xgap=7,
ygap=7,
)
)
fig.update_layout(
title="BAT, Diary, Exercise per day",
height=300,
xaxis={
"tickformat": "%a-%m-%d",
"tickangle": 75,
"showticklabels": True,
"dtick": 86400000.0 * 1, # 1 day
},
)
return fig
示例11: channels_activity
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def channels_activity (self,
colorscale:list = [
[0.0,'rgba(255,255,255,0)'],
[0.01,'rgb(255,255,200)'],
[0.25,'rgb(255,200,0)'],
[0.5,'rgb(200,0,0)'],
[0.75,'rgb(120,0,0)'],
[1.0,'rgb(0,0,0)']],
smooth_sigma:float=1,
time_bins:int=100,
width:int=None,
height:int=600,
plot_title:str="Output per channel over experiment time"):
"""
Plot a yield over time
* colorscale
a valid plotly color scale https://plot.ly/python/colorscales/ (Not recommanded to change)
* smooth_sigma
sigma parameter for the Gaussian filter line smoothing
* time_bins
Number of bins to divide the time values in (y axis)
* width
With of the plotting area in pixel
* height
height of the plotting area in pixel
* plot_title
Title to display on top of the plot
"""
self.logger.info ("\t\tComputing plot")
# Define maximal number of channels
n_channels = 3000 if self.is_promethion else 512
# Prepare all data
lab1, dd1 = self.__channels_activity_data(df_level="all", count_level="reads", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins)
lab2, dd2 = self.__channels_activity_data(df_level="pass", count_level="reads", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins)
lab3, dd3 = self.__channels_activity_data(df_level="all", count_level="bases", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins)
lab4, dd4 = self.__channels_activity_data(df_level="pass", count_level="bases", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins)
# Plot initial data
data = [go.Heatmap(x=dd1["x"][0], y=dd1["y"][0], z=dd1["z"][0], xgap=0.5, colorscale=colorscale, hoverinfo="x+y+z")]
# Create update buttons
updatemenus = [
dict (type="buttons", active=0, x=-0.06, y=0, xanchor='right', yanchor='bottom', buttons = [
dict (label=lab1, method='restyle', args=[dd1]),
dict (label=lab2, method='restyle', args=[dd2]),
dict (label=lab3, method='restyle', args=[dd3]),
dict (label=lab4, method='restyle', args=[dd4])])]
# tweak plot layout
layout = go.Layout (
plot_bgcolor="whitesmoke",
width = width,
height = height,
updatemenus = updatemenus,
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"},
xaxis = {"title":"Channel id", "zeroline":False, "showline":False, "nticks":20, "showgrid":False},
yaxis = {"title":"Experiment time (h)", "zeroline":False, "showline":False, "hoverformat":".2f", "fixedrange":True})
return go.Figure (data=data, layout=layout)
示例12: main
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def main():
"""
Wrapper for OGR
"""
parser = argparse.ArgumentParser(
description='Command line interface to python-ontobio.golr library'
"""
Provides command line interface onto the ontobio.golr python library, a high level
abstraction layer over Monarch and GO solr indices.
""",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-o', '--outfile', type=str, required=False,
help='Path to output file')
parser.add_argument('-f', '--facet', type=str, required=True,
help='Facet field to query')
parser.add_argument('-q', '--fq', type=json.loads, default={}, required=False,
help='Facet query (solr fq) - should be json')
parser.add_argument('-Q', '--qargs', type=json.loads, default={}, required=False,
help='Query to be passed directly to python golr_associations query')
parser.add_argument('-P', '--search', nargs='*', type=str, required=False,
help='Search fields. E.f subject_category object_category, relation')
parser.add_argument('-u', '--url', type=str, required=False,
help='Solr URL. E.g. http://localhost:8983/solr/golr')
parser.add_argument('-v', '--verbosity', default=0, action='count',
help='Increase output verbosity')
args = parser.parse_args()
if args.verbosity >= 2:
logging.basicConfig(level=logging.DEBUG)
elif args.verbosity == 1:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
logging.info("Welcome!")
r = search_query_as_matrix(facet=args.facet,
fq=args.fq,
facet_search_fields=args.search,
url=args.url,
**args.qargs)
print(str(r))
trace = go.Heatmap(z=r['z'],
x=r['xaxis'],
y=r['yaxis'])
data=[trace]
py.plot(data, filename='search-heatmap')
示例13: main
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def main():
"""
Wrapper for OGR
"""
parser = argparse.ArgumentParser(
description='Command line interface to python-ontobio.golr library'
"""
Provides command line interface onto the ontobio.golr python library, a high level
abstraction layer over Monarch and GO solr indices.
""",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-o', '--outfile', type=str, required=False,
help='Path to output file')
parser.add_argument('-f', '--facet', type=str, required=True,
help='Facet field to query')
parser.add_argument('-l', '--legacy_solr', dest='legacy_solr', action='store_true', default=False,
help='Set for legacy solr schema (solr3 golr)')
parser.add_argument('-q', '--fq', type=json.loads, default={}, required=False,
help='Facet query (solr fq) - should be json')
parser.add_argument('-Q', '--qargs', type=json.loads, default={}, required=False,
help='Query to be passed directly to python golr_associations query')
parser.add_argument('-P', '--pivot', nargs='*', type=str, required=False,
help='Pivot fields. E.f subject_category object_category, relation')
parser.add_argument('-u', '--url', type=str, required=False,
help='Solr URL. E.g. http://localhost:8983/solr/golr')
parser.add_argument('-v', '--verbosity', default=0, action='count',
help='Increase output verbosity')
args = parser.parse_args()
if args.verbosity >= 2:
logging.basicConfig(level=logging.DEBUG)
elif args.verbosity == 1:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
logging.info("Welcome!")
r = pivot_query_as_matrix(facet=args.facet,
fq=args.fq,
facet_pivot_fields=args.pivot,
url=args.url,
is_go=args.legacy_solr,
**args.qargs)
print(str(r))
trace = go.Heatmap(z=r['z'],
x=r['xaxis'],
y=r['yaxis'])
data=[trace]
py.plot(data, filename='pivot-heatmap')
示例14: _update_spatial_unit
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def _update_spatial_unit(self, uid, rely1, rely2, rely3, rely4, rely5,
state):
print('update_spatial_unit')
_initial = False
_update = False
if not state:
_initial = True
elif not state['data'][0]['customdata'] == uid:
_update = True
if _initial or _update:
cur_A = self.cnmf['A'].sel(unit_id=uid if not uid is None else [])
trace = [
go.Heatmap(
x=cur_A.coords['width'].values,
y=cur_A.coords['height'].values,
z=cur_A.values,
colorscale='Viridis',
colorbar=dict(x=1),
hoverinfo='none',
customdata=uid)
]
if _update:
state.update(data=trace)
if _initial:
layout = go.Layout(
title="Spatial Component of unit: {}".format(uid),
xaxis=dict(
title='width',
range=[0, self._w],
showgrid=False,
zeroline=False,
showline=True,
constrain='domain',
constraintoward='right'),
yaxis=dict(
title='height',
range=[0, self._h],
scaleanchor='x',
showgrid=False,
zeroline=False,
showline=True,
constrain='domain',
constraintoward='top'))
state = go.Figure(data=trace, layout=layout)
elif _update:
state['layout']['title'] = "Spatial Component of unit: {}".format(uid)
state = self._sync_zoom([rely1, rely2, rely3, rely4, rely5], state)
return state
示例15: _update_movies_Y
# 需要导入模块: from plotly import graph_objs [as 别名]
# 或者: from plotly.graph_objs import Heatmap [as 别名]
def _update_movies_Y(self, sig_mov, rely1, rely2, rely3, rely4, rely5,
state):
print('update movie Y')
sig_mov = json.loads(sig_mov)
_initial = False
_update = False
if state:
if not state['data'][0]['customdata'] == sig_mov:
_update = True
else:
_initial = True
if _initial or _update:
print("updating Y trace")
ts = time()
trace = [
go.Heatmap(
x=self.cur_Y.coords['width'].values,
y=self.cur_Y.coords['height'].values,
z=self.cur_Y.values,
colorscale='Viridis',
colorbar=dict(x=1),
customdata=sig_mov,
hoverinfo='none')
]
print("time spent in generating Y trace: {}".format(time() - ts))
if _update:
state.update(data=trace)
if _initial:
layout = go.Layout(
title="Y (Original) at frame: {}".format(sig_mov['f']),
xaxis=dict(
title='width',
range=[0, self._w],
showgrid=False,
zeroline=False,
showline=True,
constrain='domain',
constraintoward='right'),
yaxis=dict(
title='height',
range=[0, self._h],
scaleanchor='x',
showgrid=False,
zeroline=False,
showline=True,
constrain='domain',
constraintoward='top'))
state = go.Figure(data=trace, layout=layout)
elif _update:
state['layout']['title'] = "Y (Original) at frame: {}".format(
sig_mov['f'])
state = self._sync_zoom([rely1, rely2, rely3, rely4, rely5], state)
return state