{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### New to Plotly?\n",
"Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).\n",
"
You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).\n",
"
We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Add a Background Image"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly.plotly as py\n",
"import plotly.graph_objs as go\n",
"\n",
"import numpy as np\n",
"trace1= go.Scatter(x=[0,0.5,1,2,2.2],y=[1.23,2.5,0.42,3,1])\n",
"layout= go.Layout(images= [dict(\n",
" source= \"https://images.plot.ly/language-icons/api-home/python-logo.png\",\n",
" xref= \"x\",\n",
" yref= \"y\",\n",
" x= 0,\n",
" y= 3,\n",
" sizex= 2,\n",
" sizey= 2,\n",
" sizing= \"stretch\",\n",
" opacity= 0.5,\n",
" layer= \"below\")])\n",
"fig=go.Figure(data=[trace1],layout=layout)\n",
"py.iplot(fig,filename='EXAMPLES/background')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Add a Logo\n",
"See more examples of [adding logos to charts](https://plotly.com/python/logos/)!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly.plotly as py\n",
"import plotly.graph_objs as go\n",
"\n",
"data = [\n",
" go.Bar(\n",
" x=['-35.3', '-15.9', '-15.8', '-15.6', '-11.1',\n",
" '-9.6', '-9.2', '-3.5', '-1.9', '-0.9',\n",
" '1.0', '1.4', '1.7', '2.0', '2.8', '6.2',\n",
" '8.1', '8.5', '8.5', '8.6', '11.4', '12.5',\n",
" '13.3', '13.7', '14.4', '17.5', '17.7',\n",
" '18.9', '25.1', '28.9', '41.4'],\n",
" y=['Designers, musicians, artists, etc.',\n",
" 'Secretaries and administrative assistants',\n",
" 'Waiters and servers', 'Archivists, curators, and librarians',\n",
" 'Sales and related', 'Childcare workers, home car workers, etc.',\n",
" 'Food preparation occupations', 'Janitors, maids, etc.',\n",
" 'Healthcare technicians, assistants. and aides',\n",
" 'Counselors, social and religious workers',\n",
" 'Physical, life and social scientists', 'Construction',\n",
" 'Factory assembly workers', 'Machinists, repairmen, etc.',\n",
" 'Media and communications workers', 'Teachers',\n",
" 'Mechanics, repairmen, etc.', 'Financial analysts and advisers',\n",
" 'Farming, fishing and forestry workers',\n",
" 'Truck drivers, heavy equipment operator, etc.','Accountants and auditors',\n",
" 'Human resources, management analysts, etc.', 'Managers',\n",
" 'Lawyers and judges', 'Engineers, architects and surveyors',\n",
" 'Nurses', 'Legal support workers',\n",
" 'Computer programmers and system admin.', 'Police officers and firefighters',\n",
" 'Chief executives', 'Doctors, dentists and surgeons'],\n",
" marker=dict(\n",
" color='rgb(253, 240, 54)',\n",
" line=dict(color='rgb(0, 0, 0)',\n",
" width=2)\n",
" ),\n",
" orientation='h',\n",
" )\n",
"]\n",
"\n",
"layout = go.Layout(\n",
" images=[dict(\n",
" source=\"https://raw.githubusercontent.com/cldougl/plot_images/add_r_img/vox.png\",\n",
" xref=\"paper\", yref=\"paper\",\n",
" x=1, y=1.05,\n",
" sizex=0.2, sizey=0.2,\n",
" xanchor=\"right\", yanchor=\"bottom\"\n",
" )],\n",
" autosize=False, height=800, width=700,\n",
" bargap=0.15, bargroupgap=0.1,\n",
" barmode='stack', hovermode='x',\n",
" margin=dict(r=20, l=300,\n",
" b=75, t=125),\n",
" title='Moving Up, Moving Down
Percentile change in income between childhood and adulthood',\n",
" xaxis=dict(\n",
" dtick=10, nticks=0,\n",
" gridcolor='rgba(102, 102, 102, 0.4)',\n",
" linecolor='#000', linewidth=1,\n",
" mirror=True,\n",
" showticklabels=True, tick0=0, tickwidth=1,\n",
" title='Change in percentile',\n",
" ),\n",
" yaxis=dict(\n",
" anchor='x',\n",
" gridcolor='rgba(102, 102, 102, 0.4)', gridwidth=1,\n",
" linecolor='#000', linewidth=1,\n",
" mirror=True, showgrid=False,\n",
" showline=True, zeroline=False,\n",
" showticklabels=True, tick0=0,\n",
" type='category',\n",
" )\n",
")\n",
"fig = go.Figure(data=data, layout=layout)\n",
"py.iplot(fig,filename='EXAMPLES/logo')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Label Spectroscopy Data by Adding Multiple Images "
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly.plotly as py\n",
"import plotly.graph_objs as go\n",
"\n",
"import numpy as np\n",
"from scipy.signal import savgol_filter\n",
"\n",
"#simulate spectroscopy data\n",
"def simulated_absorption(mu,sigma,intensity):\n",
" data = [np.random.normal(mu[i],sigma[i],intensity[i]) for i in range(len(mu))]\n",
" hists = [np.histogram(d,1000,range=(200,500),normed=True) for d in data]\n",
" ys = [y for y,x in hists]\n",
" s = savgol_filter(np.max(ys,axis = 0),41,3)\n",
" return hists[0][1],s\n",
"\n",
"mus = [[290,240,260],[330,350]]\n",
"sigmas = [[4,6,10],[5,4]]\n",
"intensities = [[100000,300000,700000],[40000,20000]]\n",
"\n",
"simulated_absorptions = [simulated_absorption(m,s,i) for m,s,i in zip(mus,sigmas,intensities)]\n",
"\n",
"#create traces from data\n",
"names=['Benzene','Naphthalene']\n",
"colors = ['red','maroon']\n",
"traces = [go.Scatter(x=x,y=y,name=n,line = dict(color=c)) for (x,y),n,c in zip(simulated_absorptions,names,colors)]\n",
"\n",
"#add pictures using layout-images and then connect the image to its trace using annotations\n",
"layout= go.Layout(\n",
" images= [dict(\n",
" source= \"https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png\",\n",
" xref= \"paper\",\n",
" yref= \"paper\",\n",
" x= 0.75,\n",
" y= 0.65,\n",
" sizex= 0.3,\n",
" sizey= 0.3,\n",
" xanchor= \"right\",\n",
" yanchor= \"bottom\"\n",
" ),dict(\n",
" source= \"https://raw.githubusercontent.com/michaelbabyn/plot_data/master/naphthalene.png\",\n",
" xref=\"paper\",\n",
" yref= \"paper\",\n",
" x= 0.9,\n",
" y= 0.3,\n",
" sizex= 0.3,\n",
" sizey= 0.3,\n",
"\n",
" xanchor= \"right\",\n",
" yanchor= \"bottom\"\n",
" )\n",
" ],\n",
" annotations=[\n",
" dict(\n",
" x=93.0/300,\n",
" y=0.07/0.1,\n",
" xref='paper',\n",
" yref='paper',\n",
" showarrow=True,\n",
" arrowhead=0,\n",
" opacity=0.5,\n",
" ax=250,\n",
" ay=-40,\n",
" ),\n",
" dict(\n",
" x=156/300,\n",
" y=0.04/0.1,\n",
" xref='paper',\n",
" yref='paper',\n",
" showarrow=True,\n",
" arrowhead=0,\n",
" opacity=0.5,\n",
" ax=140,\n",
" ay=-10,\n",
" )\n",
" ],\n",
" title = 'Absorption Frequencies of Benzene and Naphthalene',\n",
" yaxis = dict(hoverformat='.3f', title='Absorption'),\n",
" xaxis = dict(title='Wavelength'),\n",
" showlegend=False,\n",
" height = 500,\n",
" width = 900\n",
" \n",
")\n",
"\n",
"fig = go.Figure(data=traces,layout=layout)\n",
"py.iplot(fig,filename='EXAMPLES/spectroscopy')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Zoom on Static Images"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly.plotly as py\n",
"import plotly.graph_objs as go\n",
"\n",
"img_width = 1600\n",
"img_height = 900\n",
"scale_factor = 0.5\n",
"\n",
"layout = go.Layout(\n",
" xaxis = go.layout.XAxis(\n",
" visible = False,\n",
" range = [0, img_width*scale_factor]),\n",
" yaxis = go.layout.YAxis(\n",
" visible=False,\n",
" range = [0, img_height*scale_factor],\n",
" # the scaleanchor attribute ensures that the aspect ratio stays constant\n",
" scaleanchor = 'x'),\n",
" width = img_width*scale_factor,\n",
" height = img_height*scale_factor,\n",
" margin = {'l': 0, 'r': 0, 't': 0, 'b': 0},\n",
" images = [go.layout.Image(\n",
" x=0,\n",
" sizex=img_width*scale_factor,\n",
" y=img_height*scale_factor,\n",
" sizey=img_height*scale_factor,\n",
" xref=\"x\",\n",
" yref=\"y\",\n",
" opacity=1.0,\n",
" layer=\"below\",\n",
" sizing=\"stretch\",\n",
" source='https://raw.githubusercontent.com/michaelbabyn/plot_data/master/bridge.jpg')]\n",
")\n",
"# we add a scatter trace with data points in opposite corners to give the Autoscale feature a reference point\n",
"fig = go.Figure(data=[{\n",
" 'x': [0, img_width*scale_factor], \n",
" 'y': [0, img_height*scale_factor], \n",
" 'mode': 'markers',\n",
" 'marker': {'opacity': 0}}],layout = layout)\n",
"py.iplot(fig, filename='EXAMPLES/zoom_bridge')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Interactive Facial Recognition Overlays"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This example requires the python library `dlib`, which can be install with pip.\n",
"\n",
"`pip install dlib`\n",
"\n",
"Note: building this library requires `cmake` to be installed and may take some time.\n",
"\n",
"Also needed are the two `.dat` files (mmod_human_face_detector.dat and mmod_dog_hipsterizer.dat) which can be downloaded [here](https://github.com/davisking/dlib-models) compressed as .gz files. Download and uncompress them in the same root directory as this example."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly.plotly as py\n",
"import plotly.graph_objs as go\n",
"\n",
"import numpy as np\n",
"import dlib\n",
"\n",
"\n",
"#load dlib's pretrained face detector\n",
"cnn_human_detector = dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')\n",
"\n",
"#choose a file in your current directory or download https://raw.githubusercontent.com/michaelbabyn/plot_data/master/beethoven.jpg\n",
"f = 'beethoven.jpg'\n",
"img = dlib.load_rgb_image(f)\n",
"\n",
"human_dets = cnn_human_detector(img,1)\n",
"\n",
"#load dlib's pretrained dog-face detector\n",
"cnn_dog_detector = dlib.cnn_face_detection_model_v1('mmod_dog_hipsterizer.dat')\n",
"\n",
"dog_dets = cnn_dog_detector(img, 1)\n",
"\n",
"layout= go.Layout(\n",
" xaxis = go.layout.XAxis(\n",
" showticklabels = False,\n",
" showgrid=False,\n",
" zeroline=False,\n",
" range = [0, img.shape[1]]\n",
" ),\n",
" yaxis = go.layout.YAxis(\n",
" showticklabels = False,\n",
" showgrid=False,\n",
" zeroline=False,\n",
" range = [0, img.shape[0]],\n",
" scaleanchor = 'x'\n",
" ),\n",
" autosize=False,\n",
" height=img.shape[0], \n",
" width=img.shape[1],\n",
" margin = {'l': 0, 'r': 0, 't': 0, 'b': 0},\n",
" images= [dict(\n",
" source= \"https://raw.githubusercontent.com/michaelbabyn/plot_data/master/beethoven.jpg\",\n",
" x=0,\n",
" sizex=img.shape[1],\n",
" y=img.shape[0],\n",
" sizey=img.shape[0],\n",
" xref=\"x\",\n",
" yref=\"y\",\n",
" opacity=1.0,\n",
" layer=\"below\",\n",
" sizing=\"stretch\"\n",
" )]\n",
")\n",
"\n",
"humans=[\n",
" go.Scatter(\n",
" x=[d.rect.left(), d.rect.right(), d.rect.right(), d.rect.left(), d.rect.left()],\n",
" y=[img.shape[0] - d.rect.top(),img.shape[0] - d.rect.top(),img.shape[0] - d.rect.bottom(),img.shape[0] - d.rect.bottom(),img.shape[0] - d.rect.top()],\n",
" hoveron = 'fills',\n",
" name = 'Human #{0}'.format(i+1),\n",
" text = 'confidence: {:.2f}'.format(d.confidence),\n",
" mode='lines',\n",
" line = dict(width=4,color='red'),\n",
" showlegend = False\n",
" ) \n",
" for i,d in enumerate(human_dets)]\n",
"\n",
"dogs = [\n",
" go.Scatter(\n",
" x=[d.rect.left(),d.rect.right(),d.rect.right(),d.rect.left(),d.rect.left()],\n",
" y=[img.shape[0] - d.rect.top(),img.shape[0] - d.rect.top(),img.shape[0] - d.rect.bottom(),img.shape[0] - d.rect.bottom(),img.shape[0] - d.rect.top()],\n",
" hoveron = 'fills',\n",
" name = 'Dog #{0}'.format(i+1),\n",
" text = 'confidence: {:.2f}'.format(d.confidence),\n",
" mode='lines',\n",
" line = dict(width=4,color='blue'),\n",
" showlegend = False\n",
" ) \n",
" for i,d in enumerate(dog_dets)]\n",
"\n",
"py.iplot(dict(data=humans+dogs,layout=layout),filename='EXAMPLES/facial_rec')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Reference\n",
"See https://plotly.com/python/reference/#layout-images for more information and chart attribute options!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"scrolled": false
},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting git+https://github.com/plotly/publisher.git\n",
" Cloning https://github.com/plotly/publisher.git to /tmp/pip-req-build-aPIGFh\n",
"Building wheels for collected packages: publisher\n",
" Running setup.py bdist_wheel for publisher ... \u001b[?25ldone\n",
"\u001b[?25h Stored in directory: /tmp/pip-ephem-wheel-cache-t99DUH/wheels/99/3e/a0/fbd22ba24cca72bdbaba53dbc23c1768755fb17b3af0f33966\n",
"Successfully built publisher\n",
"Installing collected packages: publisher\n",
" Found existing installation: publisher 0.11\n",
" Uninstalling publisher-0.11:\n",
" Successfully uninstalled publisher-0.11\n",
"Successfully installed publisher-0.11\n",
"\u001b[33mYou are using pip version 10.0.1, however version 18.0 is available.\n",
"You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n"
]
}
],
"source": [
"from IPython.display import display, HTML\n",
"\n",
"display(HTML(''))\n",
"display(HTML(''))\n",
"\n",
"! pip install git+https://github.com/plotly/publisher.git --upgrade\n",
"import publisher\n",
"publisher.publish(\n",
" 'images.ipynb', 'python/images/', 'Layout with images',\n",
" 'How to add images to charts as background images or logos.',\n",
" title = 'Layout with images | plotly',\n",
" name = 'Images',\n",
" has_thumbnail='true', thumbnail='thumbnail/images.png', \n",
" language='python',\n",
" display_as='file_settings', order=31,\n",
" ipynb= '~notebook_demo/216') "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}