def draw_all(data, output):
result = defaultdict(int)
for distro in data:
for d in distro['data']:
if d['Python_version'] not in ['', '--', '\xa0']:
result[d['Python_version']] += 1
labels = []
values = []
for k, v in sorted(result.items()):
if v > 2:
labels.append(k)
values.append(v)
trace = go.Pie(labels=labels, values=values)
py.iplot([trace], filename=output)
python类iplot()的实例源码
def draw(data, output):
result = defaultdict(int)
for distro in data:
if not distro['data']:
continue
if distro['data'][0]['Python_version'] not in ['', '--', '\xa0']:
result[distro['data'][0]['Python_version']] += 1
labels = []
values = []
for k, v in sorted(result.items()):
labels.append(k)
values.append(v)
trace = go.Pie(labels=labels, values=values)
py.iplot([trace], filename=output)
def draw6(data, output):
result = defaultdict(int)
for distro in data:
if not distro['data']:
continue
if distro['data'][0]['Python_version'] not in ['', '--', '\xa0']:
if distro['data'][0]['Python_version'].startswith('3'):
result['Python 3'] += 1
else:
result['Python 2'] += 1
labels = []
values = []
for k, v in sorted(result.items()):
labels.append(k)
values.append(v)
trace = go.Pie(labels=labels, values=values)
py.iplot([trace], filename=output)
def process(self, msg):
"""`plot: hovno`"""
params = msg.extract_parameters(self.parameters, )
from bs4 import BeautifulSoup
from yahoo_finance import Share
import plotly.plotly as py
import plotly.graph_objs as go
from dateutil.parser import parse
yahoo = Share(params['finance'])
history = yahoo.get_historical(params['date-from'],
params['date-to'])
x = [parse(d['Date']) for d in history]
data = [go.Scatter(x=x, y=[d['Close'] for d in history])]
f = py.iplot(data)
soup = BeautifulSoup(f.data, 'html.parser').find_all("iframe")[0]
msg.reply(soup.get("src"))
def _plot_option_logic(plot_options_from_call_signature):
"""
Given some plot_options as part of a plot call, decide on final options.
Precedence:
1 - Start with DEFAULT_PLOT_OPTIONS
2 - Update each key with ~/.plotly/.config options (tls.get_config)
3 - Update each key with session plot options (set by py.sign_in)
4 - Update each key with plot, iplot call signature options
"""
default_plot_options = copy.deepcopy(DEFAULT_PLOT_OPTIONS)
file_options = tools.get_config_file()
session_options = get_session_plot_options()
plot_options_from_call_signature = copy.deepcopy(plot_options_from_call_signature)
# Validate options and fill in defaults w world_readable and sharing
for option_set in [plot_options_from_call_signature,
session_options, file_options]:
utils.validate_world_readable_and_sharing_settings(option_set)
utils.set_sharing_and_world_readable(option_set)
# dynamic defaults
if ('filename' in option_set and
'fileopt' not in option_set):
option_set['fileopt'] = 'overwrite'
user_plot_options = {}
user_plot_options.update(default_plot_options)
user_plot_options.update(file_options)
user_plot_options.update(session_options)
user_plot_options.update(plot_options_from_call_signature)
user_plot_options = {k: v for k, v in user_plot_options.items()
if k in default_plot_options}
return user_plot_options
def iplot_mpl(fig, resize=True, strip_style=False, update=None,
**plot_options):
"""Replot a matplotlib figure with plotly in IPython.
This function:
1. converts the mpl figure into JSON (run help(plolty.tools.mpl_to_plotly))
2. makes a request to Plotly to save this figure in your account
3. displays the image in your IPython output cell
Positional agruments:
fig -- a figure object from matplotlib
Keyword arguments:
resize (default=True) -- allow plotly to choose the figure size
strip_style (default=False) -- allow plotly to choose style options
update (default=None) -- update the resulting figure with an 'update'
dictionary-like object resembling a plotly 'Figure' object
Additional keyword arguments:
plot_options -- run help(plotly.plotly.iplot)
"""
fig = tools.mpl_to_plotly(fig, resize=resize, strip_style=strip_style)
if update and isinstance(update, dict):
fig.update(update)
fig.validate()
elif update is not None:
raise exceptions.PlotlyGraphObjectError(
"'update' must be dictionary-like and a valid plotly Figure "
"object. Run 'help(plotly.graph_objs.Figure)' for more info."
)
return iplot(fig, **plot_options)
def ishow(cls, figure_or_data, format='png', width=None, height=None,
scale=None):
"""Display a static image of the plot described by `figure_or_data`
in an IPython Notebook.
positional arguments:
- figure_or_data: The figure dict-like or data list-like object that
describes a plotly figure.
Same argument used in `py.plot`, `py.iplot`,
see https://plot.ly/python for examples
- format: 'png', 'svg', 'jpeg', 'pdf'
- width: output width
- height: output height
- scale: Increase the resolution of the image by `scale` amount
Only valid for PNG and JPEG images.
example:
import plotly.plotly as py
fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
py.image.ishow(fig, 'png', scale=3)
"""
if format == 'pdf':
raise exceptions.PlotlyError(
"Aw, snap! "
"It's not currently possible to embed a pdf into "
"an IPython notebook. You can save the pdf "
"with the `image.save_as` or you can "
"embed an png, jpeg, or svg.")
img = cls.get(figure_or_data, format, width, height, scale)
from IPython.display import display, Image, SVG
if format == 'svg':
display(SVG(img))
else:
display(Image(img))
```
def iplot(figure_or_data, **plot_options):
"""Create a unique url for this plot in Plotly and open in IPython.
plot_options keyword agruments:
filename (string) -- the name that will be associated with this figure
fileopt ('new' | 'overwrite' | 'extend' | 'append')
- 'new': create a new, unique url for this plot
- 'overwrite': overwrite the file associated with `filename` with this
- 'extend': add additional numbers (data) to existing traces
- 'append': add additional traces to existing data lists
sharing ('public' | 'private' | 'secret') -- Toggle who can view this graph
- 'public': Anyone can view this graph. It will appear in your profile
and can appear in search engines. You do not need to be
logged in to Plotly to view this chart.
- 'private': Only you can view this plot. It will not appear in the
Plotly feed, your profile, or search engines. You must be
logged in to Plotly to view this graph. You can privately
share this graph with other Plotly users in your online
Plotly account and they will need to be logged in to
view this plot.
- 'secret': Anyone with this secret link can view this chart. It will
not appear in the Plotly feed, your profile, or search
engines. If it is embedded inside a webpage or an IPython
notebook, anybody who is viewing that page will be able to
view the graph. You do not need to be logged in to view
this plot.
world_readable (default=True) -- Deprecated: use "sharing".
Make this figure private/public
"""
if 'auto_open' not in plot_options:
plot_options['auto_open'] = False
url = plot(figure_or_data, **plot_options)
if isinstance(figure_or_data, dict):
layout = figure_or_data.get('layout', {})
else:
layout = {}
embed_options = dict()
embed_options['width'] = layout.get('width', '100%')
embed_options['height'] = layout.get('height', 525)
try:
float(embed_options['width'])
except (ValueError, TypeError):
pass
else:
embed_options['width'] = str(embed_options['width']) + 'px'
try:
float(embed_options['height'])
except (ValueError, TypeError):
pass
else:
embed_options['height'] = str(embed_options['height']) + 'px'
return tools.embed(url, **embed_options)
def save_as(cls, figure_or_data, filename, format=None, width=None,
height=None, scale=None):
"""Save a image of the plot described by `figure_or_data` locally as
`filename`.
Valid image formats are 'png', 'svg', 'jpeg', and 'pdf'.
The format is taken as the extension of the filename or as the
supplied format.
positional arguments:
- figure_or_data: The figure dict-like or data list-like object that
describes a plotly figure.
Same argument used in `py.plot`, `py.iplot`,
see https://plot.ly/python for examples
- filename: The filepath to save the image to
- format: 'png', 'svg', 'jpeg', 'pdf'
- width: output width
- height: output height
- scale: Increase the resolution of the image by `scale` amount
Only valid for PNG and JPEG images.
example:
import plotly.plotly as py
fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]}
py.image.save_as(fig, 'my_image.png', scale=3)
```
"""
# todo: format shadows built-in name
(base, ext) = os.path.splitext(filename)
if not ext and not format:
filename += '.png'
elif ext and not format:
format = ext[1:]
elif not ext and format:
filename += '.' + format
img = cls.get(figure_or_data, format, width, height, scale)
f = open(filename, 'wb')
f.write(img)
f.close()
```