from ggplot import * from bokeh import pyplot import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({"x": range(100), "y": np.random.choice([-1, 1], 100)}) df.y = df.y.cumsum() g = ggplot(aes(x="x", y="y"), data=df) + geom_step() g.draw() plt.title("Step ggplot-based plot in Bokeh.") pyplot.show_bokeh(plt.gcf(), filename="step.html")
from bokeh import pyplot from pylab import * from bokeh import plotting x = linspace(-2*pi,2*pi,100) y = sin(x) plot(x,y,"r-") title("Matplotlib Figure in Bokeh") # dashed lines work #plot(x,y,"r-x", linestyle="-.") pyplot.show_bokeh(gcf(), filename="mpltest.html") plotting.session().dumpjson(file="mpltest.json")
plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('I', fontsize=20) plt.subplot(222) plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20)) plt.ylabel('II', fontsize=20) plt.subplot(223) plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.ylabel('III', fontsize=20) plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) xfit = np.array([np.amin(x4), np.amax(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('IV', fontsize=20) # We create the figure in matplotlib and then we "pass it" to Bokeh pyplot.show_bokeh(plt.gcf(), filename="subplots.html") plotting.session().dumpjson(file="subplots.json")
# Generate data. In this case, we'll make a bunch of center-points and generate # verticies by subtracting random offsets from those center-points numpoly, numverts = 100, 4 centers = 100 * (np.random.random((numpoly,2)) - 0.5) offsets = 10 * (np.random.random((numverts,numpoly,2)) - 0.5) verts = centers + offsets verts = np.swapaxes(verts, 0, 1) # In your case, "verts" might be something like: # verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...) # If "data" in your case is a numpy array, there are cleaner ways to reorder # things to suit. colors = ['red','green','blue','cyan','yellow','magenta','black'] ax = plt.axes() # Make the collection and add it to the plot. col = PolyCollection(verts, color=colors) ax.add_collection(col) plt.xlim([-60, 60]) plt.ylim([-60, 60]) plt.title("MPL-PolyCollection support in Bokeh") pyplot.show_bokeh(plt.gcf(), filename="mpl_polycollection.html") plotting.session().dumpjson(file="mpl_polycollection.json")
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x='price', color='cut')) + \ geom_density() g.draw() plt.title("xkcd-ggplot-mpl based plot in Bokeh.") pyplot.show_bokeh(plt.gcf(), filename="xkcd_density.html", xkcd=True)
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x='price', color='cut')) + \ geom_density() g.draw() plt.title("Density ggplot-based plot in Bokeh.") pyplot.show_bokeh(name="density")
# colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] # colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), # (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] colors = ['r', 'g', 'b', 'c', 'y', 'm', 'k'] widths = [5, 10, 20, 40, 20, 10, 5] segments = make_segments(x, y) lc = LineCollection(segments, colors=colors, linewidth=widths, alpha=alpha) ax = plt.gca() ax.add_collection(lc) return lc # Colored sine wave x = np.linspace(0, 4 * np.pi, 100) y = np.sin(x) colorline(x, y) plt.title("MPL support for ListCollection in Bokeh") plt.xlim(x.min(), x.max()) plt.ylim(-1.0, 1.0) pyplot.show_bokeh(plt.gcf(), filename="mpl_listcollection.html") plotting.session().dumpjson(file="mpl_listcollection.json")
import numpy as np import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from bokeh import pyplot # Generate the pandas dataframe data = np.random.multivariate_normal([0, 0], [[1, 2], [2, 20]], size=100) data = pd.DataFrame(data, columns=["X", "Y"]) mpl.rc("figure", figsize=(6, 6)) # Just plot seaborn kde sns.kdeplot(data, cmap="BuGn_d") plt.title("Seaborn kdeplot in bokeh.") pyplot.show_bokeh(name="kde")
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(aes(x='date', y='beef'), data=meat) + \ geom_line() g.draw() plt.title("Line ggplot-based plot in Bokeh.") pyplot.show_bokeh(name="line")
import numpy as np import matplotlib.pyplot as plt from bokeh import pyplot x = np.linspace(-2 * np.pi, 2 * np.pi, 100) y = np.sin(x) z = np.cos(x) plt.plot(x, y, "r-", marker='o') plt.title("Matplotlib Figure in Bokeh") # dashed lines work plt.plot(x, z, "g-x", linestyle="-.") #pyplot.show_bokeh() #pyplot.show_bokeh(name="test") pyplot.show_bokeh(plt.gcf(), name="test") #pyplot.show_bokeh(plt.gcf(), server="default") #pyplot.show_bokeh(plt.gcf(), name="test", server="default")
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(aes(x='date', y='beef'), data=meat) + \ geom_line() g.draw() plt.title("Line ggplot-based plot in Bokeh.") pyplot.show_bokeh(plt.gcf(), filename="line.html")
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from bokeh import pyplot # We generated random data data = 1 + np.random.randn(20, 6) # And then just call the violinplot from Seaborn sns.violinplot(data, color="Set3") plt.title("Seaborn violin plot in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="violin.html")
from ggplot import * from bokeh import pyplot import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({"x": range(100), "y": np.random.choice([-1, 1], 100)}) df.y = df.y.cumsum() g = ggplot(aes(x='x', y='y'), data=df) + \ geom_step() g.draw() plt.title("Step ggplot-based plot in Bokeh.") pyplot.show_bokeh(plt.gcf(), filename="step.html")
# Generate data. In this case, we'll make a bunch of center-points and generate # verticies by subtracting random offsets from those center-points numpoly, numverts = 100, 4 centers = 100 * (np.random.random((numpoly, 2)) - 0.5) offsets = 10 * (np.random.random((numverts, numpoly, 2)) - 0.5) verts = centers + offsets verts = np.swapaxes(verts, 0, 1) # In your case, "verts" might be something like: # verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...) # If "data" in your case is a numpy array, there are cleaner ways to reorder # things to suit. colors = ['red', 'green', 'blue', 'cyan', 'yellow', 'magenta', 'black'] ax = plt.axes() # Make the collection and add it to the plot. col = PolyCollection(verts, color=colors) ax.add_collection(col) plt.xlim([-60, 60]) plt.ylim([-60, 60]) plt.title("MPL-PolyCollection support in Bokeh") pyplot.show_bokeh(plt.gcf(), filename="polycollection.html") plotting.session().dumpjson(file="polycollection.json")
from ggplot import * from bokeh import pyplot import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ "x": range(100), "y": np.random.choice([-1, 1], 100) }) df.y = df.y.cumsum() g = ggplot(aes(x='x', y='y'), data=df) + \ geom_step() g.draw() plt.title("Step ggplot-based plot in Bokeh.") pyplot.show_bokeh(name="step")
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import optimize from bokeh import pyplot # Set the palette colors. sns.set(palette="Set2") # Build the sin wave def sine_wave(n_x, obs_err_sd=1.5, tp_err_sd=.3): x = np.linspace(0, (n_x - 1) / 2, n_x) y = np.sin(x) + np.random.normal(0, obs_err_sd) + np.random.normal(0, tp_err_sd, n_x) return y sines = np.array([sine_wave(31) for _ in range(20)]) # Generate the Seaborn plot with "ci" bars. ax = sns.tsplot(sines, err_style="ci_bars", interpolate=False) xmin, xmax = ax.get_xlim() x = np.linspace(xmin, xmax, sines.shape[1]) out, _ = optimize.leastsq(lambda p: sines.mean(0) - (np.sin(x / p[1]) + p[0]), (0, 2)) a, b = out xx = np.linspace(xmin, xmax, 100) plt.plot(xx, np.sin(xx / b) + a, c="#444444") plt.title("Seaborn tsplot with CI in bokeh.") pyplot.show_bokeh(name="sinerror")
import matplotlib.pyplot as plt from scipy import optimize from bokeh import pyplot from bokeh import plotting # Set the palette colors. sns.set(palette="Set2") # Build the sin wave def sine_wave(n_x, obs_err_sd=1.5, tp_err_sd=.3): x = np.linspace(0, (n_x - 1) / 2, n_x) y = np.sin(x) + np.random.normal(0, obs_err_sd) + np.random.normal(0, tp_err_sd, n_x) return y sines = np.array([sine_wave(31) for _ in range(20)]) # Generate the Seaborn plot with "ci" bars. ax = sns.tsplot(sines, err_style="ci_bars", interpolate=False) xmin, xmax = ax.get_xlim() x = np.linspace(xmin, xmax, sines.shape[1]) out, _ = optimize.leastsq(lambda p: sines.mean(0) - (np.sin(x / p[1]) + p[0]), (0, 2)) a, b = out xx = np.linspace(xmin, xmax, 100) plt.plot(xx, np.sin(xx / b) + a, c="#444444"); plt.title("Seaborn tsplot with CI in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="mpl_seaborn_sinerror.html") plotting.session().dumpjson(file="mpl_seaborn_sinerror.json")
# verticies by subtracting random offsets from those center-points numpoly, numverts = 100, 4 centers = 100 * (np.random.random((numpoly, 2)) - 0.5) offsets = 10 * (np.random.random((numverts, numpoly, 2)) - 0.5) verts = centers + offsets verts = np.swapaxes(verts, 0, 1) # In your case, "verts" might be something like: # verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...) # If "data" in your case is a numpy array, there are cleaner ways to reorder # things to suit. facecolors = ["red", "green", "blue", "cyan", "yellow", "magenta", "black"] edgecolors = ["cyan", "yellow", "magenta", "black", "red", "green", "blue"] widths = [5, 10, 20, 10, 5] ax = plt.axes() # Make the collection and add it to the plot. col = PolyCollection(verts, facecolor=facecolors, edgecolor=edgecolors, linewidth=widths, linestyle="--", alpha=0.5) ax.add_collection(col) plt.xlim([-60, 60]) plt.ylim([-60, 60]) plt.title("MPL-PolyCollection support in Bokeh") pyplot.show_bokeh(name="polycollection")
import numpy as np import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from bokeh import pyplot from bokeh import plotting # Generate the pandas dataframe data = np.random.multivariate_normal([0, 0], [[1, 2], [2, 20]], size=100) data = pd.DataFrame(data, columns=["X", "Y"]) mpl.rc("figure", figsize=(6, 6)) # Just plot seaborn kde sns.kdeplot(data, cmap="BuGn_d") plt.title("Seaborn kdeplot in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="seaborn_kde.html") plotting.session().dumpjson(file="seaborn_kde.json")
import numpy as np import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from bokeh import pyplot # Generate the pandas dataframe data = np.random.multivariate_normal([0, 0], [[1, 2], [2, 20]], size=100) data = pd.DataFrame(data, columns=["X", "Y"]) mpl.rc("figure", figsize=(6, 6)) # Just plot seaborn kde sns.kdeplot(data, cmap="BuGn_d") plt.title("Seaborn kdeplot in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="kde.html")
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x='price', color='cut')) + \ geom_density() g.draw() plt.title("Density ggplot-based plot in Bokeh.") pyplot.show_bokeh(plt.gcf(), filename="density.html")
def plot_index(self, data, name='Index', nb=True, datarange=None, xticks=10, xticks_fontsize=10, dateformat=False, figsize=(10, 8), xmargin=True, ymargin=True, legend=True, smoother=None, output=None, dpi=300, grid=True, xlabel='Year', ylabel='', title='', win_size=10, win_type='boxcar', center=False, std=0.1, beta=0.1, power=1, width=1, min_periods=None, freq=None, scategory=None, frac=1. / 3, it=3, figsave=None, prov=False): """ Function to plot the Climate Forcing indicator for the ESR 2013, it follow graphic guidlines from the past ESR adding functionalities like : several kind of smoothline with different :param data: pandas dataframe - input data :param name: string - name used as dataframe index :param nb: bolean if True the function is optimized to render the png inside a notebook :param datarange: list of 2 integer for mak min year :param xticks: integer xtick spacing default=10 :param xticks_fontsize: integer xticks fontsize default=10 :param dateformat: boolean if True set the xticks labels in date format :param figsize: tuple figure size default (10, 8) :param xmargin: bolean default True :param ymargin: bolean default True :param legend: bolean default True :param smoother: tuple (f,i) :param output: directory where to save output default None :param dpi: integer :param grid: bolean default True :param xlabel: string default 'Year' :param ylabel: string default '' :param title: string default '' :param win_size: integer default 10 :param win_type: string default 'boxcar' :param center: bolean default False :param std: float default 0.1 :param beta: float default 0.1 :param power: integer default 1 :param width: integer default 1 :param min_periods: None :param freq: None :param str scategory: default 'rolling' :param float frac: default 0.6666666666666666 Between 0 and 1. The fraction of the data used when estimating each y-value., :param int it: default 3 The number of residual-based reweightings to perform. """ try: assert type(data) == pd.core.frame.DataFrame #x = data.index.year #y = data.values if datarange: #if datarange != None : mind = np.datetime64(str(datarange[0])) maxd = np.datetime64(str(datarange[1])) newdata = data.ix[mind:maxd] x = newdata.index.year y = newdata.values else: x = data.index.year y = data.values x_p = x[np.where(y >= 0)[0]] y_p = y[np.where(y >= 0)[0]] x_n = x[np.where(y < 0)[0]] y_n = y[np.where(y < 0)[0]] fig = plt.figure(figsize=figsize) ax1 = fig.add_subplot(111) ax1.bar(x_n, y_n, 0.8, facecolor='b', label=name + ' < 0') ax1.bar(x_p, y_p, 0.8, facecolor='r', label=name + ' > 0') ax1.grid(grid) if ylabel != '': ax1.set_ylabel(ylabel) else: ax1.set_ylabel(name) if xlabel != '': ax1.set_xlabel(xlabel) else: ax1.set_xlabel(xlabel) if title == '': ax1.set_title(name) else: ax1.set_title(title) ax1.axhline(0, color='black', lw=1.5) if xmargin: ax1.set_xmargin(0.1) if ymargin: ax1.set_xmargin(0.1) if legend: ax1.legend() if not figsave: figsave = name + '.png' if scategory == 'rolling': newy = self.rolling_smoother(data, stype=smoother, win_size=win_size, win_type=win_type, center=center, std=std, beta=beta, power=power, width=width) ax1.plot(newy.index.year, newy.values, lw=3, color='g') if scategory == 'expanding': newy = self.expanding_smoother(data, stype=smoother, min_periods=min_periods, freq=freq) ax1.plot(newy.index.year, newy.values, lw=3, color='g') if scategory == 'lowess': x = np.array(range(0, len(data.index.values))).T newy = pd.Series(lowess(data.values.flatten(), x, frac=frac, it=it).T[1], index=data.index) ax1.plot(newy.index.year, newy, lw=3, color='g') ## interp 1D attempt xx = np.linspace(min(data.index.year), max(data.index.year), len(newy)) f = interp1d(xx, newy) xnew = np.linspace(min(data.index.year), max(data.index.year), len(newy) * 4) f2 = interp1d(xx, newy, kind='cubic') #xnew = np.linspace(min(data.index.values), max(data.index.values), len(newy)*2) ax1.plot(xx, newy, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--') ## if scategory == 'ewma': print('todo') plt.xticks(data.index.year[::xticks].astype('int'), data.index.year[::xticks].astype('int'), fontsize=xticks_fontsize) plt.autoscale(enable=True, axis='both', tight=True) if dateformat: fig.autofmt_xdate(bottom=0.2, rotation=75, ha='right') if output: eu.ensure_dir(output) ffigsave = os.path.join(output, figsave) plt.savefig(ffigsave, dpi=dpi) print('graph saved in: %s ' % ffigsave) if scategory: smoutput = name + '_' + scategory + '.csv' if smoother: smoutput = name + '_' + scategory + '_' + smoother + '.csv' smoutput = os.path.join(output, smoutput) if scategory == 'lowess': newdataframe = data.copy(deep=True) newdataframe['smooth'] = pd.Series(newy, index=data.index) newdataframe.to_csv(smoutput, sep=',', header=True, index=True, index_label='Year') else: newy.to_csv(smoutput, sep=',', header=True, index=True, index_label='Year') print(name + ' smoothed data saved in : %s ' % smoutput) if nb: fig.subplots_adjust(left=-1.0) fig.subplots_adjust(right=1.0) #plt.show() if prov: function = {} function['name'] = 'plot_index' function['parameters'] = {} function['parameters']['data'] = data function['parameters']['name'] = name function['parameters']['nb'] = nb function['parameters']['datarange'] = datarange function['parameters']['xticks'] = xticks function['parameters']['xticks_fontsize'] = xticks_fontsize function['parameters']['dateformat'] = dateformat function['parameters']['figsize'] = figsize function['parameters']['xmargin'] = xmargin function['parameters']['ymargin'] = ymargin function['parameters']['legend'] = legend function['parameters']['smoother'] = smoother function['parameters']['output'] = output function['parameters']['dpi'] = dpi function['parameters']['grid'] = grid function['parameters']['xlabel'] = xlabel function['parameters']['ylabel'] = ylabel function['parameters']['title'] = title function['parameters']['win_size'] = win_size function['parameters']['win_type'] = win_type function['parameters']['center'] = center function['parameters']['std'] = std function['parameters']['beta'] = beta function['parameters']['power'] = power function['parameters']['width'] = width function['parameters']['min_periods'] = min_periods function['parameters']['freq'] = freq function['parameters']['scategory'] = scategory function['parameters']['frac'] = frac function['parameters']['it'] = it function['parameters']['figsave'] = figsave jsonld = { "@id": "ex:NAO_figure", "@type": ["prov:Entity", "ecoop:Figure"], "ecoop_ext:hasData": "ecoop_data['NAO']", "ecoop_ext:hasCode": { "@type": "ecoop_ext:Code", "ecoop_ext:hasFunction_src_code_link": "", "ecoop_ext:hasParameter": [ { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "beta", "ecoop_ext:parameter_value": beta }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "center", "ecoop_ext:parameter_value": center }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "data", "ecoop_ext:parameter_value": data }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "datarange", "ecoop_ext:parameter_value": datarange }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "dateformat", "ecoop_ext:parameter_value": dateformat }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "dpi", "ecoop_ext:parameter_value": dpi }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "figsave", "ecoop_ext:parameter_value": figsave }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "figsize", "ecoop_ext:parameter_value": figsize }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "frac", "ecoop_ext:parameter_value": frac }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "freq", "ecoop_ext:parameter_value": freq }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "grid", "ecoop_ext:parameter_value": grid }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "it", "ecoop_ext:parameter_value": it }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "legend", "ecoop_ext:parameter_value": legend }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "min_periods", "ecoop_ext:parameter_value": min_periods }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "name", "ecoop_ext:parameter_value": name }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "nb", "ecoop_ext:parameter_value": nb }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "output", "ecoop_ext:parameter_value": output }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "power", "ecoop_ext:parameter_value": power }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "scategory", "ecoop_ext:parameter_value": scategory }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "smoother", "ecoop_ext:parameter_value": smoother }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "std", "ecoop_ext:parameter_value": std }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "title", "ecoop_ext:parameter_value": title }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "width", "ecoop_ext:parameter_value": width }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "win_size", "ecoop_ext:parameter_value": win_size }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "win_type", "ecoop_ext:parameter_value": win_type }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "xlabel", "ecoop_ext:parameter_value": xlabel }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "xmargin", "ecoop_ext:parameter_value": xmargin }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "xticks", "ecoop_ext:parameter_value": xticks }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "xticks_fontsize", "ecoop_ext:parameter_value": xticks_fontsize }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "ylabel", "ecoop_ext:parameter_value": ylabel }, { "@type": "ecoop_ext:Parameter", "ecoop_ext:parameter_name": "ymargin", "ecoop_ext:parameter_value": ymargin } ] }, "ecoop_ext:usedSoftware": [{"@id": "ex:ecoop_software"}, {"@id": "ex:ipython_software"}] } display('cell-output metadata saved', metadata={'ecoop_prov': jsonld}) pyplot.show_bokeh(plt.gcf(), filename="subplots.html") except AssertionError: if type(data) != pd.core.frame.DataFrame: print('input data not compatible, it has to be of type : pandas.core.frame.DataFrame') print('data not loaded correctly')
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import optimize from bokeh import pyplot # Set the palette colors. sns.set(palette="Set2") # Build the sin wave def sine_wave(n_x, obs_err_sd=1.5, tp_err_sd=.3): x = np.linspace(0, (n_x - 1) / 2, n_x) y = np.sin(x) + np.random.normal(0, obs_err_sd) + np.random.normal(0, tp_err_sd, n_x) return y sines = np.array([sine_wave(31) for _ in range(20)]) # Generate the Seaborn plot with "ci" bars. ax = sns.tsplot(sines, err_style="ci_bars", interpolate=False) xmin, xmax = ax.get_xlim() x = np.linspace(xmin, xmax, sines.shape[1]) out, _ = optimize.leastsq(lambda p: sines.mean(0) - (np.sin(x / p[1]) + p[0]), (0, 2)) a, b = out xx = np.linspace(xmin, xmax, 100) plt.plot(xx, np.sin(xx / b) + a, c="#444444") plt.title("Seaborn tsplot with CI in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="sinerror.html")
import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from bokeh import pyplot from bokeh import plotting # In order to efficiently plot many lines in a single set of axes, # add the lines all at once. Here is a simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x + i for i in x] colors = [ '#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000' ] line_segments = LineCollection([list(zip(x, y)) for y in ys], color=colors, linewidth=(0.5, 1, 1.5, 2), linestyle='dashed') ax = plt.axes() ax.add_collection(line_segments) ax.set_title('Line Collection with dashed colors') pyplot.show_bokeh(plt.gcf(), filename="lc_dashed.html") plotting.session().dumpjson(file="lc_dashed.json")
import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from bokeh import pyplot from bokeh import plotting # In order to efficiently plot many lines in a single set of axes, # add the lines all at once. Here is a simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x+i for i in x] colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] line_segments = LineCollection([list(zip(x,y)) for y in ys], color=colors, linewidth=(0.5,1,1.5,2), linestyle='dashed') ax = plt.axes() ax.add_collection(line_segments) ax.set_title('Line Collection with dashed colors') pyplot.show_bokeh(plt.gcf(), filename="lc_dashed.html") plotting.session().dumpjson(file="lc_dashed.json")
import numpy as np import matplotlib.pyplot as plt from bokeh import pyplot x = np.linspace(-2 * np.pi, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y, "r-") plt.title("Matplotlib Figure in Bokeh") # dashed lines work #plt.plot(x,y,"r-x", linestyle="-.") pyplot.show_bokeh(plt.gcf(), filename="test.html")
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x="price", color="cut")) + geom_density() g.draw() plt.title("xkcd-ggplot-mpl based plot in Bokeh.") pyplot.show_bokeh(plt.gcf(), filename="xkcd_density.html", xkcd=True)
import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from bokeh import pyplot # In order to efficiently plot many lines in a single set of axes, # add the lines all at once. Here is a simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x + i for i in x] colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] line_segments = LineCollection([list(zip(x, y)) for y in ys], color=colors, linewidth=(0.5, 1, 1.5, 2), linestyle='dashed') ax = plt.axes() ax.add_collection(line_segments) ax.set_title('Line Collection with dashed colors') pyplot.show_bokeh(name="lc_dashed")
# You have several ways to input the colors: # colors = ['r','g','b','c','y','m','k'] # colors = ['red','green','blue','cyan','yellow','magenta','black'] # colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] # colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), # (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] colors = ['r', 'g', 'b', 'c', 'y', 'm', 'k'] widths = [5, 10, 20, 40, 20, 10, 5] segments = make_segments(x, y) lc = LineCollection(segments, colors=colors, linewidth=widths, alpha=alpha) ax = plt.gca() ax.add_collection(lc) return lc # Colored sine wave x = np.linspace(0, 4 * np.pi, 100) y = np.sin(x) colorline(x, y) plt.title("MPL support for ListCollection in Bokeh") plt.xlim(x.min(), x.max()) plt.ylim(-1.0, 1.0) pyplot.show_bokeh(name="listcollection")
plt.subplot(221) plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('I', fontsize=20) plt.subplot(222) plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20)) plt.ylabel('II', fontsize=20) plt.subplot(223) plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.ylabel('III', fontsize=20) plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) xfit = np.array([np.amin(x4), np.amax(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('IV', fontsize=20) # We create the figure in matplotlib and then we "pass it" to Bokeh pyplot.show_bokeh(name="subplots")
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from bokeh import pyplot from bokeh import plotting # We generated random data data = 1 + np.random.randn(20, 6) # And then just call the violinplot from Seaborn sns.violinplot(data, color="Set3") plt.title("Seaborn violin plot in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="mpl_seaborn_violet.html") plotting.session().dumpjson(file="mpl_seaborn_violet.json")
from ggplot import * from bokeh import pyplot import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x='price', color='cut')) + \ geom_density() g.draw() plt.title("xkcd-ggplot-mpl based plot in Bokeh.") pyplot.show_bokeh(name="xkcd_density", xkcd=True)
# Set the palette colors. sns.set(palette="Set2") # Build the sin wave def sine_wave(n_x, obs_err_sd=1.5, tp_err_sd=.3): x = np.linspace(0, (n_x - 1) / 2, n_x) y = np.sin(x) + np.random.normal(0, obs_err_sd) + np.random.normal( 0, tp_err_sd, n_x) return y sines = np.array([sine_wave(31) for _ in range(20)]) # Generate the Seaborn plot with "ci" bars. ax = sns.tsplot(sines, err_style="ci_bars", interpolate=False) xmin, xmax = ax.get_xlim() x = np.linspace(xmin, xmax, sines.shape[1]) out, _ = optimize.leastsq(lambda p: sines.mean(0) - (np.sin(x / p[1]) + p[0]), (0, 2)) a, b = out xx = np.linspace(xmin, xmax, 100) plt.plot(xx, np.sin(xx / b) + a, c="#444444") plt.title("Seaborn tsplot with CI in bokeh.") pyplot.show_bokeh(plt.gcf(), filename="seaborn_sinerror.html") plotting.session().dumpjson(file="seaborn_sinerror.json")
# a "waterfall" plot or a "stagger" plot. nverts = 60 ncurves = 20 offs = (0.1, 0.0) rs = np.random.RandomState([12345678]) yy = np.linspace(0, 2*np.pi, nverts) ym = np.amax(yy) xx = (0.2 + (ym-yy)/ym)**2 * np.cos(yy-0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02*rs.randn(nverts) curve = list(zip(xxx, yy*100)) segs.append(curve) colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] col = LineCollection(segs, linewidth=5, offsets=offs) ax = plt.axes() ax.add_collection(col, autolim=True) col.set_color(colors) ax.set_title('Successive data offsets') fig = plt.gcf() pyplot.show_bokeh(plt.gcf(), filename="mpl_lc_offsets.html") plotting.session().dumpjson(file="mpl_lc_offsets.json")
# a "waterfall" plot or a "stagger" plot. nverts = 60 ncurves = 20 offs = (0.1, 0.0) rs = np.random.RandomState([12345678]) yy = np.linspace(0, 2 * np.pi, nverts) ym = np.amax(yy) xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02 * rs.randn(nverts) curve = list(zip(xxx, yy * 100)) segs.append(curve) colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] col = LineCollection(segs, linewidth=5, offsets=offs) ax = plt.axes() ax.add_collection(col, autolim=True) col.set_color(colors) ax.set_title('Successive data offsets') fig = plt.gcf() pyplot.show_bokeh(name="lc_offsets")
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from bokeh import pyplot # We generated random data data = 1 + np.random.randn(20, 6) # And then just call the violinplot from Seaborn sns.violinplot(data, color="Set3") plt.title("Seaborn violin plot in bokeh.") pyplot.show_bokeh(name="violin")
# colors = ['red','green','blue','cyan','yellow','magenta','black'] # colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] # colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), # (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] colors = ['r','g','b','c','y','m','k'] widths = [5, 10, 20, 40, 20, 10, 5] segments = make_segments(x, y) lc = LineCollection(segments, colors=colors, linewidth=widths, alpha=alpha) ax = plt.gca() ax.add_collection(lc) return lc # Colored sine wave x = np.linspace(0, 4 * np.pi, 100) y = np.sin(x) colorline(x, y) plt.title("MPL support for ListCollection in Bokeh") plt.xlim(x.min(), x.max()) plt.ylim(-1.0, 1.0) pyplot.show_bokeh(plt.gcf(), filename="listcollection.html") plotting.session().dumpjson(file="listcollection.json")