Example #1
0
def when_I_call_placeholder_insert_chart(context):
    chart_data = CategoryChartData()
    chart_data.categories = ["Yes", "No"]
    chart_data.add_series("Series 1", (42, 24))
    placeholder = context.shape
    context.placeholder = placeholder.insert_chart(XL_CHART_TYPE.PIE,
                                                   chart_data)
def create_bar_chart(details, base=None):
    print("This is bar chart function")
    if len(details["categories"]) != len(details["values"]):
        return False, "Couldn't create the bar chart as the number of categories and values are not equal"

    try:
        prs = Presentation('./Final - Presentation.pptx')
    except exc.PackageNotFoundError as err:
        # print(f'No presentation file: {err}')
        prs = Presentation(base)
    slide = prs.slides.add_slide(prs.slide_layouts[10])

    chart_data = CategoryChartData()

    try:
        values = (float(i) for i in details["values"])
    except ValueError as err:
        print(f'Cannot extract values from list: {err}')
        return False, "Couldn't create the bar chart due to invalid numeric values"

    chart_data.add_series('Series 1', values)
    chart_data.categories = details["categories"]

    x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)

    slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy,
                           chart_data)

    if 'title' in details:
        slide.placeholders[0].text = details['title'].title()
        # chart.chart_title.text_frame.text = details['title'].title()

    prs.save('Final - Presentation.pptx')
    print("Hello")
    return True, "Created the Bar Chart"
Example #3
0
    def pie_simple(self, question, slide):
        categories = []
        frequencies = []
        for response in question.responses:
            categories.append(str(response.response))
            for year, frequency in response.frequencies.items():
                frequencies.append(frequency)
        chart_data = CategoryChartData()
        chart_data.categories = categories
        chart_data.add_series('Series 1', iter(frequencies))
        left, top, width, height = Inches(6.75), Inches(2), Inches(
            6.5), Inches(5)

        chart = slide.shapes.add_chart(XL_CHART_TYPE.PIE, left, top, width,
                                       height, chart_data).chart
        chart.chart_title.has_text_frame = True
        chart.chart_title.text_frame.text = "Q: " + str(question.prompt)
        chart.chart_title.text_frame.paragraphs[0].font.size = Pt(12)
        chart.has_legend = True
        chart.legend.position = XL_LEGEND_POSITION.BOTTOM
        chart.legend.font.size = Pt(12)
        chart.legend.include_in_layout = False
        chart.plots[0].has_data_labels = True
        data_labels = chart.plots[0].data_labels
        if question.stat == 'percent':
            data_labels.number_format = '0%'
        data_labels.font.size = Pt(12)
def create_bar_chart(slide,
                     x_axis,
                     y_axis,
                     values,
                     chart_dim,
                     chart_type,
                     cp,
                     title=None,
                     label_flag=None):
    chart_data = CategoryChartData()
    chart_data.categories = x_axis
    for i in range(len(y_axis)):
        chart_data.add_series(y_axis[i], values[i])
    x, y, cx, cy = chart_dim[0], chart_dim[1], chart_dim[2], chart_dim[3]
    graphic_frame = slide.shapes.add_chart(chart_type, x, y, cx, cy,
                                           chart_data)
    chart = graphic_frame.chart
    if title:
        title_tf = chart.chart_title.text_frame
        title_tf.text = title
        title_font = title_tf.paragraphs[0].font
        title_font.size, title_font.bold, title_font.name = Pt(
            14), True, "Proxima Nova"
        title_font.color.rgb = RGBColor(128, 128, 128)
    cp(chart, y_axis, label_flag)
Example #5
0
    def bar_clustered_matrix_by_scale_points(self, question, slide):
        sub_questions = question.questions
        series_names = []  # responses
        series_lists = []  # frequencies for each scale point
        categories = []  # scale points
        is_first = True

        for sub_question in sub_questions:
            #series_names.append(str(sub_question.prompt) + " (n=" + str(sub_question.n) + ")")
            if is_first:
                for response in sub_question.responses:
                    categories.append(response.response)
                question.stat = sub_question.stat
            is_first = False

        for name in series_names:
            frequencies = []
            series_lists.append([])
        response_idx = 0
        for sub_question in sub_questions:
            frequencies = series_lists[response_idx]
            for response in sub_question.responses:
                if response.has_frequency is True:
                    for year, frequency in response.frequencies.items():
                        frequencies.append(frequency)
                else:
                    frequencies.append(0)
            response_idx += 1

        chart_data = CategoryChartData()
        chart_data.categories = categories
        for idx in range(0, len(series_names)):
            chart_data.add_series(series_names[idx], iter(series_lists[idx]))
        left, top, width, height = Inches(6.75), Inches(2), Inches(
            6.5), Inches(5)

        chart = slide.shapes.add_chart(XL_CHART_TYPE.BAR_CLUSTERED, left, top,
                                       width, height, chart_data).chart
        chart.chart_title.has_text_frame = True
        chart.chart_title.text_frame.text = "Q: " + str(question.prompt)
        chart.chart_title.text_frame.paragraphs[0].font.size = Pt(12)

        category_axis = chart.category_axis
        category_axis.has_minor_gridlines = False
        category_axis.has_major_gridlines = False
        category_axis.tick_labels.font.size = Pt(12)
        value_axis = chart.value_axis
        value_axis.has_minor_gridlines = False
        value_axis.has_major_gridlines = False
        value_axis.tick_labels.font.size = Pt(12)
        chart.plots[0].has_data_labels = True
        data_labels = chart.plots[0].data_labels
        if question.stat == 'percent':
            data_labels.number_format = '0%'
        data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
        data_labels.font.size = Pt(12)
        chart.has_legend = True
        chart.legend.position = XL_LEGEND_POSITION.BOTTOM
        chart.legend.font.size = Pt(12)
        chart.legend.include_in_layout = False
Example #6
0
def __create_chartdata(chartInfo):
    chart_data = CategoryChartData()

    # TODO: Deal with First Row as Labels and Column Names as Labels

    colNames = chartInfo['data'][0].columns.tolist()
    offset = 0

    if (chartInfo['first_column_as_labels']):
        offset = 1

    if len(colNames) > offset:

        colNum = 1
        for colName in colNames[offset:]:
            if (chartInfo['column_names_as_labels']):
                chart_data.categories.add_category(colName)
            else:
                chart_data.categories.add_category('Category ' + str(colNum))

        rowNum = 1
        for index, row in chartInfo['data'][0].iterrows():
            data = []
            for colName in colNames[offset:]:
                data.append(row[colName])

            if chartInfo['first_column_as_labels']:
                chart_data.add_series(str(row[0]), data)
            else:
                chart_data.add_series('Series ' + str(rowNum), data)

    return chart_data
Example #7
0
def create_pie_chart(details, base=None):

    if len(details["categories"]) != len(details["percentages"]):
        return False, "Couldn't create the pie chart as the number of categories and percentage values are not equal"

    # prs = Presentation()
    # slide = prs.slides.add_slide(prs.slide_layouts[5])

    try:
        prs = Presentation('./Final - Presentation.pptx')
    except exc.PackageNotFoundError as err:
        # print(f'No presentation file: {err}')
        prs = Presentation(base)
    slide = prs.slides.add_slide(prs.slide_layouts[10])

    chart_data = CategoryChartData()

    x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)

    chart_data = ChartData()
    # chart_data.categories = ['West', 'East', 'North', 'South', 'Other']
    # chart_data.add_series('Series 1', (0.135, 0.324, 0.180, 0.235, 0.126))

    try:
        percent_floats = [float(i) for i in details["percentages"]]
    except ValueError as err:
        print(f'Cannot extract number from percentages: {err}')
        return False, "Couldn't create the pie chart due to invalid percentage values"

    if sum(percent_floats) != 100.0 and sum(percent_floats) != 1.0:
        return False, "Couldn't create the pie chart as percentages don't add up to 100"

    if sum(percent_floats) == 100.0:
        temp = percent_floats
        percent_floats = [i / 100.0 for i in temp]

    chart_data.add_series('Series 1', percent_floats)

    chart_data.categories = details["categories"]

    chart = slide.shapes.add_chart(XL_CHART_TYPE.PIE, x, y, cx, cy,
                                   chart_data).chart

    chart.has_legend = True
    chart.legend.position = XL_LEGEND_POSITION.BOTTOM
    chart.legend.include_in_layout = False

    chart.plots[0].has_data_labels = True
    data_labels = chart.plots[0].data_labels
    data_labels.number_format = '0%'
    data_labels.position = XL_DATA_LABEL_POSITION.OUTSIDE_END

    if 'title' in details:
        slide.placeholders[0].text = details['title'].title()
        # chart.chart_title.text_frame.text = details['title'].title()

    prs.save('Final - Presentation.pptx')

    return True, "Created the Pie Chart"
Example #8
0
 def rewrite_fixture(self):
     ser_xml, expected_xml = snippet_seq('rewrite-ser')[:2]
     chart_data = CategoryChartData()
     chart_data.categories = ('foo', 'bar')
     series_data = chart_data.add_series('Series 1', (1, 2))
     rewriter = _CategorySeriesXmlRewriter(chart_data)
     ser = parse_xml(ser_xml)
     return rewriter, ser, series_data, expected_xml
Example #9
0
 def df2chart_data(df):
     """index转换为chart_data的categories,columns转为chart_data的series"""
     chart_data = CategoryChartData()
     df.fillna('', inplace=True)
     chart_data.categories = df.index.tolist()
     for col in df:
         chart_data.add_series(col, df[col].tolist())
     return chart_data
Example #10
0
def given_a_CategoryChartData_object_having_date_categories(context):
    chart_data = CategoryChartData()
    chart_data.categories = [
        datetime.date(2016, 12, 27),
        datetime.date(2016, 12, 28),
        datetime.date(2016, 12, 29),
    ]
    context.chart_data = chart_data
Example #11
0
def when_I_assign_shapes_add_chart_to_shape(context):
    chart_data = CategoryChartData()
    chart_data.categories = ('Foo', 'Bar')
    chart_data.add_series('East', (1.0, 2.0))
    chart_data.add_series('West', (3.0, 4.0))

    context.shape = context.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED,
                                             Inches(1), Inches(1), Inches(8),
                                             Inches(5), chart_data)
Example #12
0
    def pandas_to_ppt_chart_data(dataframe):
        assert isinstance(dataframe, pd.DataFrame)

        data = CategoryChartData()
        col_lst = dataframe.columns.to_list()
        data.categories = col_lst

        for i, r in dataframe.iterrows():
            data.add_series(str(i), tuple([r[col] for col in col_lst]))

        return data
Example #13
0
 def rewrite_fixture(self, request):
     snippet_offset, categories = request.param
     chart_data = CategoryChartData()
     chart_data.categories = categories
     rewriter = _CategorySeriesXmlRewriter(chart_data)
     snippets = snippet_seq("rewrite-ser")
     ser_xml = snippets[snippet_offset]
     ser = parse_xml(ser_xml)
     series_data = chart_data.add_series("Series 1", (1, 2))
     expected_xml = snippets[snippet_offset + 1]
     return rewriter, ser, series_data, expected_xml
Example #14
0
    def it_can_generate_xml_for_multi_level_cat_charts(self):
        chart_data = CategoryChartData()
        WEST = chart_data.add_category("WEST")
        WEST.add_sub_category("SF")
        WEST.add_sub_category("LA")
        EAST = chart_data.add_category("EAST")
        EAST.add_sub_category("NY")
        EAST.add_sub_category("NJ")
        chart_data.add_series("Series 1", (1, 2, None, 4))
        chart_data.add_series("Series 2", (5, None, 7, 8))
        xml_writer = _BarChartXmlWriter(XL_CHART_TYPE.BAR_CLUSTERED, chart_data)

        assert xml_writer.xml == snippet_text("4x2-multi-cat-bar")
 def add_ser_fixture(self, CategorySeriesData_, series_):
     chart_data = CategoryChartData()
     name, values, number_format = "foobar", iter((1, 2, 3)), "0.0"
     calls = [call(1), call(2), call(3)]
     return (
         chart_data,
         name,
         values,
         number_format,
         CategorySeriesData_,
         calls,
         series_,
     )
Example #16
0
def _(values: DataFrame, chart: Chart) -> None:
    """Renders into the given chart the values in the DataFrame."""

    chart_data = CategoryChartData()

    chart_data.categories = list(values.index)

    for label in list(values):
        chart_data.add_series(label, list(values[label].values))

    if hasattr(values, 'title'):
        chart.chart_title.text_frame.text = values.title

    chart.replace_data(chart_data)
Example #17
0
def _(values: DataFrame, chart: Chart) -> None:
    """Renders into the given chart the values in the DataFrame."""

    chart_data = CategoryChartData()

    chart_data.categories = values['categories']

    for label, series in values['data'].items():
        chart_data.add_series(label, series)

    if 'title' in values:
        chart.chart_title.text_frame.text = values['title']

    chart.replace_data(chart_data)
Example #18
0
def addSerieToChart(presentation, index_chart, serie_name, serie):
    count_chart = 0
    for _slide_i, slide in enumerate(presentation.slides):
        for shape in slide.shapes:
            if shape.has_chart:
                if count_chart == index_chart:
                    chart_data = CategoryChartData()
                    chart_data.categories = ("Critical", "Major", "Important", "Minor")
                    chart_data.add_series(serie_name, serie)
                    shape.chart.replace_data(chart_data)
                    shape.chart.value_axis.maximum_scale = max(serie)+1
                    return True
                count_chart += 1
    return False
Example #19
0
def make_category_chart_data(cat_count, ser_count):
    """
    Return a |CategoryChartData| instance populated with *cat_count*
    categories and *ser_count* series. Values are auto-generated.
    """
    category_names = ('Foo', 'Bar', 'Baz', 'Boo', 'Far', 'Faz')
    point_values = count(1.1, 1.1)
    chart_data = CategoryChartData()
    chart_data.categories = category_names[:cat_count]
    for idx in range(ser_count):
        series_title = 'Series %d' % (idx + 1)
        series_values = tuple(islice(point_values, cat_count))
        series_values = [round(x * 10) / 10.0 for x in series_values]
        chart_data.add_series(series_title, series_values)
    return chart_data
Example #20
0
def buildChartData(series, database, start_date):
    df = Haver.data(series, database, start_date)
    ##Temp fix
    if series.__contains__('csent'):
        df = df[:-1]
    df = df.asfreq('D', how='start')
    df.index = df.index.strftime('%m/%d/%Y')
    df.index = pd.to_datetime(df.index)
    chart_data = CategoryChartData()
    chart_data.categories = df.index
    
    for x in series:
        chart_data.add_series(x, df[x])
    
    return df, chart_data
Example #21
0
def ChartData_from_DataFrame(df, number_format="0%", xl_number_format='0.00%'):
    """
    Return a CategoryChartData instance from the given Pandas DataFrame.
    """
    def get_parent(sub_categories, line, pos):
        """
        Return the sub_category's parent given its lineage position.
        """

        for subcat in sub_categories:
            if subcat.label == line[pos]:
                return subcat

    cd = CategoryChartData(number_format=number_format)

    if isinstance(df.index, pd.MultiIndex):
        cats = []
        for line in df.index.unique().tolist():
            for l, lvl in enumerate(line):
                if l == 0:
                    if not any([lvl == cat.label for cat in cats]):
                        cats.append(cd.add_category(lvl))
                else:
                    parent = get_parent(cats, line, 0)
                    if l > 1:
                        for i in range(1, l):
                            parent = get_parent(parent.sub_categories, line, i)
                    sub_categories = parent.sub_categories
                    seen = [lvl == subcat.label for subcat in sub_categories]
                    if not any(seen):
                        parent.add_sub_category(lvl)
    else:
        categories = tuple(df.index.values.tolist())
        cd.categories = categories

    for col in df.columns:
        values = [
            value if value == value else None
            for value in df[col].values.tolist()
        ]
        if isinstance(col, tuple):
            series = (" - ".join(col), tuple(values))
        else:
            series = (col, tuple(values))

        cd.add_series(*series, number_format=xl_number_format)

    return cd
Example #22
0
    def bar_chart(self, categories, values, title, number):

        # define chart data ---------------------
        #slide = self.presentation.slides.add_slide(self.presentation.slide_layouts[5])
        slide = self.presentation.slides[number]
        shapes = slide.shapes
        shapes.title.text = title
        # define chart data ---------------------
        chart_data = CategoryChartData()
        chart_data.categories = categories
        chart_data.add_series('Series 2', (element for element in values))

        # add chart to slide --------------------
        x, y, cx, cy = Inches(2), Inches(1), Inches(6), Inches(4.5)
        slide.shapes.add_chart(
            XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data)
Example #23
0
    def __pandas_genelate_linechart(self, df):
        '''
        プライベートメソッド。
        pandasのデータフレームをpptxのchartに変換

        Args:
            df (pandas.DataFrame): 出力したいdataframe

        return:
            chart_data (pptx.chart.data.CategoryChartData): chartデータ
        '''
        chart_data = CategoryChartData()
        chart_data.categories = df.index
        for column in df.columns:
            chart_data.add_series(column, df[column])
        return chart_data
Example #24
0
    def bar_clustered_basic_trended(self, question, slide):
        headers = self.max_years(question.responses)
        series_lists = []
        categories = []
        for header in headers:
            frequencies = []
            series_lists.append(frequencies)
        for response in question.responses:
            categories.append(str(response.response))
            header_idx = 0
            for header in headers:
                frequencies = series_lists[header_idx]
                if response.frequencies.get(header) is not None:
                    freq = response.frequencies.get(header)
                    frequencies.append(freq)
                header_idx += 1
        chart_data = CategoryChartData()
        chart_data.categories = categories
        for idx in range(0, len(headers)):
            chart_data.add_series(str(headers[idx]), iter(series_lists[idx]))
        left, top, width, height = Inches(6.75), Inches(2), Inches(
            6.5), Inches(5)

        chart = slide.shapes.add_chart(XL_CHART_TYPE.BAR_CLUSTERED, left, top,
                                       width, height, chart_data).chart
        chart.chart_title.has_text_frame = True
        chart.chart_title.text_frame.text = "Q: " + str(question.prompt)
        chart.chart_title.text_frame.paragraphs[0].font.size = Pt(12)
        chart.has_legend = False
        category_axis = chart.category_axis
        category_axis.has_minor_gridlines = False
        category_axis.has_major_gridlines = False
        category_axis.tick_labels.font.size = Pt(12)
        value_axis = chart.value_axis
        value_axis.has_minor_gridlines = False
        value_axis.has_major_gridlines = False
        value_axis.tick_labels.font.size = Pt(12)
        chart.plots[0].has_data_labels = True
        data_labels = chart.plots[0].data_labels
        if question.stat == 'percent':
            data_labels.number_format = '0%'
        data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
        data_labels.font.size = Pt(12)
        chart.has_legend = True
        chart.legend.position = XL_LEGEND_POSITION.BOTTOM
        chart.legend.font.size = Pt(12)
        chart.legend.include_in_layout = False
Example #25
0
    def multi_fixture(self):
        chart_data = CategoryChartData()

        WEST = chart_data.add_category('WEST')
        WEST.add_sub_category('SF')
        WEST.add_sub_category('LA')
        EAST = chart_data.add_category('EAST')
        EAST.add_sub_category('NY')
        EAST.add_sub_category('NJ')

        chart_data.add_series('Series 1', (1, 2, None, 4))
        chart_data.add_series('Series 2', (5, None, 7, 8))

        xml_writer = _BarChartXmlWriter(XL_CHART_TYPE.BAR_CLUSTERED,
                                        chart_data)
        expected_xml = snippet_text('4x2-multi-cat-bar')
        return xml_writer, expected_xml
Example #26
0
def when_I_add_a_clustered_bar_chart_with_multi_level_categories(context):
    chart_type = XL_CHART_TYPE.BAR_CLUSTERED
    chart_data = CategoryChartData()

    WEST = chart_data.add_category('WEST')
    WEST.add_sub_category('SF')
    WEST.add_sub_category('LA')
    EAST = chart_data.add_category('EAST')
    EAST.add_sub_category('NY')
    EAST.add_sub_category('NJ')

    chart_data.add_series('Series 1', (1, 2, None, 4))
    chart_data.add_series('Series 2', (5, None, 7, 8))

    context.chart = context.slide.shapes.add_chart(chart_type, Inches(1),
                                                   Inches(1), Inches(8),
                                                   Inches(5), chart_data).chart
def when_I_add_a_clustered_bar_chart_with_multi_level_categories(context):
    chart_type = XL_CHART_TYPE.BAR_CLUSTERED
    chart_data = CategoryChartData()

    WEST = chart_data.add_category("WEST")
    WEST.add_sub_category("SF")
    WEST.add_sub_category("LA")
    EAST = chart_data.add_category("EAST")
    EAST.add_sub_category("NY")
    EAST.add_sub_category("NJ")

    chart_data.add_series("Series 1", (1, 2, None, 4))
    chart_data.add_series("Series 2", (5, None, 7, 8))

    context.chart = context.slide.shapes.add_chart(
        chart_type, Inches(1), Inches(1), Inches(8), Inches(5), chart_data
    ).chart
Example #28
0
    def multi_fixture(self):
        chart_data = CategoryChartData()

        WEST = chart_data.add_category("WEST")
        WEST.add_sub_category("SF")
        WEST.add_sub_category("LA")
        EAST = chart_data.add_category("EAST")
        EAST.add_sub_category("NY")
        EAST.add_sub_category("NJ")

        chart_data.add_series("Series 1", (1, 2, None, 4))
        chart_data.add_series("Series 2", (5, None, 7, 8))

        xml_writer = _BarChartXmlWriter(XL_CHART_TYPE.BAR_CLUSTERED,
                                        chart_data)
        expected_xml = snippet_text("4x2-multi-cat-bar")
        return xml_writer, expected_xml
Example #29
0
 def get_chart_stack(self, heading, data):
     slide = self.prs.slides.add_slide(self.prs.slide_layouts[5])
     title = slide.shapes.title
     title.text = heading
     chart_data = CategoryChartData()
     chart_data.categories = data.keys()
     chart_data.add_series('served by each LP', data.values())
     x, y, cx, cy = Inches(1), Inches(2), Inches(8), Inches(5)
     chart = slide.shapes.add_chart(
         XL_CHART_TYPE.COLUMN_CLUSTERED, 
         x, 
         y, 
         cx, 
         cy, 
         chart_data,
         )
     chart.has_legend = True
Example #30
0
 def create(self):
     """
     builds & returns the PPTX object
     """
     data_frames = self.data_frames
     p = Presentation()
     layout = p.slide_layouts[6]
     for frame in data_frames:
         cd = CategoryChartData()
         cd.categories = frame.index
         for name in frame.columns:
             cd.add_series(name, frame[name], '0%')
         slide = p.slides.add_slide(layout)
         chart_type = self._chart_type()
         shape = slide.shapes.add_chart(chart_type, 0, 0, 9143301, 6158000,
                                        cd)
     return p