示例#1
0
def temp_graph(xdata, ydata, w, h):
    '''A helper function to plot data
    Args
    Returns
    '''
    plt = figure(plot_width=w, plot_height=h)
    plt.line(xdata, ydata, line_width=2)
    plt.circle(xdata, ydata, fill_color="white", size=8)
    return plt
示例#2
0
def generate_rec_prec_html(mrec, mprec, scores, class_name, ap):
    """
     generate dynamic P-R curve HTML page for each class
    """
    # bypass invalid class
    if len(mrec) == 0 or len(mprec) == 0 or len(scores) == 0:
        return

    rec_prec_plot_path = os.path.join('result', 'classes')
    os.makedirs(rec_prec_plot_path, exist_ok=True)
    bokeh_io.output_file(os.path.join(rec_prec_plot_path,
                                      class_name + '.html'),
                         title='P-R curve for ' + class_name)

    # prepare curve data
    area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]
    area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]
    score_on_curve = [0.0] + scores[:-1] + [0.0] + [scores[-1]] + [1.0]
    source = bokeh.models.ColumnDataSource(
        data={
            'rec': area_under_curve_x,
            'prec': area_under_curve_y,
            'score': score_on_curve,
        })

    # prepare plot figure
    plt_title = 'class: ' + class_name + ' AP = {}%'.format(ap * 100)
    plt = bokeh_plotting.figure(plot_height=200,
                                plot_width=200,
                                tools="",
                                toolbar_location=None,
                                title=plt_title,
                                sizing_mode="scale_width")
    plt.background_fill_color = "#f5f5f5"
    plt.grid.grid_line_color = "white"
    plt.xaxis.axis_label = 'Recall'
    plt.yaxis.axis_label = 'Precision'
    plt.axis.axis_line_color = None

    # draw curve data
    plt.line(x='rec', y='prec', line_width=2, color='#ebbd5b', source=source)
    plt.add_tools(
        bokeh.models.HoverTool(tooltips=[
            ('score', '@score{0.0000 a}'),
            ('Prec', '@prec'),
            ('Recall', '@rec'),
        ],
                               formatters={
                                   'rec': 'printf',
                                   'prec': 'printf',
                               },
                               mode='vline'))
    bokeh_io.save(plt)
    return
示例#3
0
def get_chart(chart_type, data, **kwargs):
    plt.switch_backend('AGG')
    fig = plt.figure(figsize=(10, 4))
    if chart_type == "#1":
        print("bar chart")
        plt.bar(data['transaction_id'], data['price'])
    elif chart_type == "#2":
        labels = kwargs.get('labels')
        plt.pie(data=data, x='price', labels=labels)
        print("pie chart")
    elif chart_type == "#3":
        plt.line(data['transaction_id'], data['price'])
        print("line chart")
    else:
        print("chart generation failed")
    plt.tight_layout()
    chart = get_graph()
    return chart
示例#4
0
def main():
    N = 4
    localnetMeans = (20, 35, 30, 35) #LAN length of outage (mins)
    wanMeans = (25, 32, 34, 20) #WAN length of outage (min)
    ind = np.arange(N)    # the x locations for the groups
    # the width of the bars: can also be len(x) sequence
    width = 0.35

    # describe where to display p
    # stack p2 on top of p1
    p1 = plt.line(ind, localnetMeans, width)
    p2 = plt.line(ind, wanMeans, width, bottom=localnetMeans)

    # Describe the table metadata
    plt.ylabel("Length of Outage (mins)")
    plt.title("2018 Network Summary")
    plt.xticks(ind, ("Q1", "Q2", "Q3", "Q4"))
    plt.yticks(np.arange(0, 81, 10))
    plt.legend((p1[0], p2[0]), ("LAN", "WAN"))

    # display the graph
    # plt.show() # you can try this on a Python IDE with a GUI if you'd like
    plt.savefig("/home/student/mycode/graphing/2018summary.pdf")
示例#5
0
def Stock_intchart(ticker, ndays=180):
    today = dt.date.today()
    data = yfs.get_data(ticker, start_date=today - dt.timedelta(days=ndays), end_date=today)
    fig = plt.line(data, y='close', title=ticker)

    fig.update_xaxes(rangeslider_visible=True,rangeselector=dict(
            buttons=list([
                dict(count=15, label="15d", step="day", stepmode="backward"),
                dict(count=1, label="1m", step="month", stepmode="backward"),
                dict(count=3, label="3m", step="year", stepmode="backward"),
                dict(step="all")
            ])
        )
    )
    fig.show()
# -*- coding: utf-8 -*-
"""
Created on Thu Aug  6 16:30:55 2020

@author: pulki
"""


%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize']=(20.0,10.0)

data=pd.read_csv('E:/analytics/datasets/headbrain.csv')
data.shape
data.head()

X=data['Head Size(cm^3)'].values
Y=data['Brain Weight(grams)'].values

ax=plt.scatter(X,Y)
plt.line(X,Y)
plt.title('Linear Regression')
plt.xlabel("Head Size")
plt.ylabel('Brain Weight')
示例#7
0
def plot_powspec_binned_bokeh(data: Dict,
                              lmax: Dict,
                              title_string: str,
                              truthfile=None,
                              truth_label: str = None) -> None:
    """Plotting

    Args:
        data (Dict): powerspectra with spectrum and frequency-combinations in the columns
        plotsubtitle (str, optional): Add characters to the title. Defaults to 'default'.
        plotfilename (str, optional): Add characters to the filename. Defaults to 'default'
    """
    # koi = next(iter(data.keys()))
    # specs = list(data[koi].keys())

    bins = np.logspace(np.log10(1), np.log10(lmax + 1), 250)
    bl = bins[:-1]
    br = bins[1:]

    from bokeh.plotting import figure as bfigure
    plt = bfigure(title=title_string,
                  y_axis_type="log",
                  x_axis_type="log",
                  x_range=(10, 4000),
                  y_range=(1e-3, 1e6),
                  background_fill_color="#fafafa")
    # plt.xlabel("Multipole l")
    # plt.ylabel("Powerspectrum")

    idx = 0
    idx_max = 8
    from bokeh.palettes import inferno
    for freqc, val in data.items():
        col = inferno(idx_max)
        freqs = freqc.split("-")
        if freqs[0] == freqs[1]:
            binmean, binerr, _ = _std_dev_binned(data[freqc])
            binerr_low = np.array([
                binmean[n] * 0.01 if binerr[n] > binmean[n] else binerr[n]
                for n in range(len(binerr))
            ])
            plt.line(
                0.5 * bl + 0.5 * br,
                np.nan_to_num(binmean),
                legend_label=freqc + " Channel",
                # yerr=(binerr_low, binerr),
                # # 0.5 * bl + 0.5 * br,
                # # binmean,
                # # yerr=binerr,
                # label=freqc,
                # capsize=2,
                # elinewidth=1,
                # fmt='x',
                # # ls='-',
                # ms=4,
                # alpha=(2*idx_max-idx)/(2*idx_max)
                color=col[idx],
                line_width=3,
                muted_alpha=0.2)
            plt.multi_line(  #[(bm, bm) for bm in np.nan_to_num(binmean)]
                [(bx, bx) for bx in 0.5 * bl + 0.5 * br],
                [(bm - br, bm + br) for bm, br in zip(np.nan_to_num(binmean),
                                                      np.nan_to_num(binerr))],
                legend_label=freqc + " Channel",
                # yerr=(binerr_low, binerr),
                # # 0.5 * bl + 0.5 * br,
                # # binmean,
                # # yerr=binerr,
                # label=freqc,
                # capsize=2,
                # elinewidth=1,
                # fmt='x',
                # # ls='-',
                # ms=4,
                # alpha=(2*idx_max-idx)/(2*idx_max)
                line_color=col[idx],
                line_width=2,
                muted_alpha=0.2)
            idx += 1
            plt.xaxis.axis_label = "Multipole l"
            plt.yaxis.axis_label = "Powerspectrum"

    plt.line(np.arange(0, 4000, 1),
             truthfile,
             color='red',
             line_width=4,
             legend_label="Best Planck EE",
             muted_alpha=0.2)
    # label = truth_label,
    # ls='-', marker='.',
    # ms=0,
    # lw=3)
    plt.legend.location = "top_left"
    plt.legend.click_policy = "mute"
    return plt
示例#8
0
sales = sales.set_index('date')
print(sales.head(5))

y = sales['item_cnt_day'].resample('MS').sum()
y = y.diff()

plt.style.use('fivethirtyeight')
y.plot(figsize=(15, 6))
plt.show()

plt.style.use('ggplot')
decomposition = sm.tsa.seasonal_decompose(y, model='additive')
fig = decomposition.plot()
plt.show()

plt.line()

decomposition = sm.tsa.seasonal_decompose(y, model='multiplicative')
fig = decomposition.plot()
plt.show()

print(sales.info())

monthly_sales = sales.groupby(["date_block_num", "shop_id",
                               "item_id"])["date", "item_price",
                                           "item_cnt_day"].agg({
                                               "date": ["min", 'max'],
                                               "item_price":
                                               "mean",
                                               "item_cnt_day":
                                               "sum"
示例#9
0
                  level='glyph',
                  x_offset=-17.5,
                  y_offset=0,
                  source=source,
                  text_font_size='14pt',
                  render_mode='canvas')
plt.add_layout(labels)

# plot
a = plt.vbar(x='kod', top='cases', width=0.8, source=source)
a.glyph.fill_color = '#084594'

r = {}
r['in_pop'] = plt.line(x='kod',
                       y='in_pop',
                       color='red',
                       source=source,
                       y_range_name='procenty',
                       legend_label='share in the population')
r['increment'] = plt.circle(x='kod',
                            y='increment',
                            size=20,
                            color='green',
                            source=source,
                            y_range_name='procenty',
                            legend_label='daily increment ')

# legenda
plt.legend.location = 'top_right'
plt.legend.click_policy = 'hide'

# tabela do layout'u
示例#10
0
def cum_sum(Y):
    Y['cum_sum'] = Y['spot_counts'].cumsum()
    Y.reset_index(inplace=True)
    return Y


# Z=group.apply(cum_sum)

group = good_check.groupby([
    'market', 'station_name', 'daypart_name', 'invcode_name', 'air_week',
    'air_year'
])

bad_check = Bad_Data[Bad_Data.invcode_name == 'Today Show 7-8a']

plt.line('')

normal_pile = data[data['sport_olympic_flag'] == 'normal']
sport_pile = data[data['sport_olympic_flag'] == 'sports']
olympic_pile = data[data['sport_olympic_flag'] == 'olympic']

# Good Pile

Fit_TS = normal_pile[(normal_pile['time_series_flag'] == 'fit')]
Good_Data = Fit_TS[Fit_TS['spot_flag'] == 'good']

# Bad_Pile

Unfit_TS = normal_pile[(normal_pile['time_series_flag'] == 'unfit')]
Fit_Bad_Spot = Fit_TS[Fit_TS['spot_flag'] == 'bad']
Bad_Data = Unfit_TS.append(Fit_Bad_Spot)
示例#11
0
import matplotlib.pyplot as pt  #importing matplotlib pt is an alias of pyplot
import pandas as pd
#importing pandas , pd is an elias of pandas
#If we want to read something from dataset or csv file we use read_csv() method.
data = pd.read_csv("../../matplotlib/cgpa.csv")
data = data.head(40)
# head() method is used to select some elements of dataset
#here i am plotting rollno vs cgpa so x-axis will be rollno and y-axis will be cgpa
#color of scatter is blue and we also include label as scatter.
#scatter() method is used to plot the scatter
pt.line(data["rollno"], data["cgpa"], color="blue", label="scatter")

pt.xlabel("RollNo", color="green")  #xlabel() defines the label of x-axis
pt.ylabel("CGPA", color="blue")  #ylabel() defines the label of x-axis
pt.title("CGPA vs Roll No",
         color="green")  #title() is used to give title of this scatter plot
pt.show()