Middle-题目110:2. Add Two Numbers

本文介绍了一种使用链表表示数字并进行加法运算的方法。通过两种实现方式:一是利用BigInteger进行计算;二是模拟竖式计算过程。两种方法分别在Java和C中实现。

题目原文:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目大意:
给出两个数,用链表逆序的存储每个数位,求他们的和,并也用链表逆序存储数位。
题目分析:
方法一:用BigInteger储存两个数字,再加起来,再生成对应链表。
方法二:模拟整数竖式算法(好在是逆序的, 正序就麻烦了)
源码:(language:java/c)
方法一:

import java.math.BigInteger;

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        BigInteger num1 = BigInteger.ZERO;
        BigInteger num2 = BigInteger.ZERO;
        BigInteger temp = BigInteger.ONE;

        while(l1!=null) {
            //num1+=temp*l1.val;
            num1=num1.add(temp.multiply(BigInteger.valueOf(l1.val)));
            temp=temp.multiply(BigInteger.TEN);
            l1=l1.next;
        }
        temp=BigInteger.ONE;
        while(l2!=null) {
            num2=num2.add(temp.multiply(BigInteger.valueOf(l2.val)));
            temp=temp.multiply(BigInteger.TEN);
            l2=l2.next;
        }
        BigInteger sum = num1.add(num2);
        if(sum.compareTo(BigInteger.ZERO)==0)
            return new ListNode(0);
        else {
            ListNode l = new ListNode(sum.mod(BigInteger.TEN).intValue());
            ListNode p=l;
            while(sum.compareTo(BigInteger.ZERO)!=0) {
                sum=sum.divide(BigInteger.TEN);
                if(sum.compareTo(BigInteger.ZERO)!=0) {
                    p.next = new ListNode(sum.mod(BigInteger.TEN).intValue());
                    p=p.next;
                }
            }
            return l;
        }
    }
}

方法二:(from discuss)

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* result = l1 ? l1 : l2;
    struct ListNode* carry = l1 ? l2 : l1;
    struct ListNode* node = result;
    struct ListNode* tmp;
    int c = 0;
    int s;
    while (l1 || l2) {
        s = c;
        if (l1) { s += l1->val; l1=l1->next; }
        if (l2) { s += l2->val; l2=l2->next; }
        c = s > 9 ? 1 : 0;
        node->val = c ? s - 10 : s;
        if (l1) {
            node = node->next = l1;
        } else if (l2) {
            node = node->next = l2;
        } else {
            node->next = NULL;
        }
    }
    if (c) {
        carry->val = c;
        node->next = carry;
        node = node->next;
    }
    node->next = NULL;
    return result;
}

成绩:
方法一:28ms,beats 1.57%,众数4ms,63.50%
方法二:20ms,beats 18.86%,众数20ms,68.68%

D:\Users\J60109516\Desktop\project\NEW_predict\plotly1.py:61: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy Traceback (most recent call last): File "D:\Users\J60109516\Desktop\project\NEW_predict\plotly1.py", line 76, in <module> fig.update_layout( File "D:\Python\Lib\site-packages\plotly\graph_objs\_figure.py", line 218, in update_layout return super().update_layout(dict1, overwrite, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python\Lib\site-packages\plotly\basedatatypes.py", line 1415, in update_layout self.layout.update(dict1, overwrite=overwrite, **kwargs) File "D:\Python\Lib\site-packages\plotly\basedatatypes.py", line 5195, in update BaseFigure._perform_update(self, kwargs, overwrite=overwrite) File "D:\Python\Lib\site-packages\plotly\basedatatypes.py", line 3971, in _perform_update BaseFigure._perform_update(plotly_obj[key], val) File "D:\Python\Lib\site-packages\plotly\basedatatypes.py", line 3949, in _perform_update raise err ValueError: Invalid property specified for object of type plotly.graph_objs.layout.YAxis: 'titlefont' Did you mean "tickfont"? Valid properties: anchor If set to an opposite-letter axis id (e.g. `x2`, `y`), this axis is bound to the corresponding opposite-letter axis. If set to "free", this axis' position is determined by `position`. automargin Determines whether long tick labels automatically grow the figure margins. autorange Determines whether or not the range of this axis is computed in relation to the input data. See `rangemode` for more info. If `range` is provided and it has a value for both the lower and upper bound, `autorange` is set to False. Using "min" applies autorange only to set the minimum. Using "max" applies autorange only to set the maximum. Using *min reversed* applies autorange only to set the minimum on a reversed axis. Using *max reversed* applies autorange only to set the maximum on a reversed axis. Using "reversed" applies autorange on both ends and reverses the axis direction. autorangeoptions :class:`plotly.graph_objects.layout.yaxis.Autorangeopti ons` instance or dict with compatible properties autoshift Automatically reposition the axis to avoid overlap with other axes with the same `overlaying` value. This repositioning will account for any `shift` amount applied to other axes on the same side with `autoshift` is set to true. Only has an effect if `anchor` is set to "free". autotickangles When `tickangle` is set to "auto", it will be set to the first angle in this array that is large enough to prevent label overlap. autotypenumbers Using "strict" a numeric string in trace data is not converted to a number. Using *convert types* a numeric string in trace data may be treated as a number during automatic axis `type` detection. Defaults to layout.autotypenumbers. calendar Sets the calendar system to use for `range` and `tick0` if this is a date axis. This does not set the calendar for interpreting data on this axis, that's specified in the trace or via the global `layout.calendar` categoryarray Sets the order in which categories on this axis appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. categoryarraysrc Sets the source reference on Chart Studio Cloud for `categoryarray`. categoryorder Specifies the ordering logic for the case of categorical variables. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. Set `categoryorder` to *total ascending* or *total descending* if order should be determined by the numerical order of the values. Similarly, the order can be determined by the min, max, sum, mean, geometric mean or median of all the values. color Sets default for all colors associated with this axis all at once: line, font, tick, and grid colors. Grid color is lightened by blending this with the plot background Individual pieces can override this. constrain If this axis needs to be compressed (either due to its own `scaleanchor` and `scaleratio` or those of the other axis), determines how that happens: by increasing the "range", or by decreasing the "domain". Default is "domain" for axes containing image traces, "range" otherwise. constraintoward If this axis needs to be compressed (either due to its own `scaleanchor` and `scaleratio` or those of the other axis), determines which direction we push the originally specified plot area. Options are "left", "center" (default), and "right" for x axes, and "top", "middle" (default), and "bottom" for y axes. dividercolor Sets the color of the dividers Only has an effect on "multicategory" axes. dividerwidth Sets the width (in px) of the dividers Only has an effect on "multicategory" axes. domain Sets the domain of this axis (in plot fraction). dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. fixedrange Determines whether or not this axis is zoom-able. If true, then zoom is disabled. gridcolor Sets the color of the grid lines. griddash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). gridwidth Sets the width (in px) of the grid lines. hoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" insiderange Could be used to set the desired inside range of this axis (excluding the labels) when `ticklabelposition` of the anchored axis has "inside". Not implemented for axes with `type` "log". This would be ignored when `range` is provided. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. layer Sets the layer on which this axis is displayed. If *above traces*, this axis is displayed above all the subplot's traces If *below traces*, this axis is displayed below all the subplot's traces, but above the grid lines. Useful when used together with scatter-like traces with `cliponaxis` set to False to show markers and/or text nodes above this axis. linecolor Sets the axis line color. linewidth Sets the width (in px) of the axis line. matches If set to another axis id (e.g. `x2`, `y`), the range of this axis will match the range of the corresponding axis in data-coordinates space. Moreover, matching axes share auto-range values, category lists and histogram auto-bins. Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint is currently forbidden. Moreover, note that matching axes must have the same `type`. maxallowed Determines the maximum range of this axis. minallowed Determines the minimum range of this axis. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". minor :class:`plotly.graph_objects.layout.yaxis.Minor` instance or dict with compatible properties minorloglabels Determines how minor log labels are displayed. If *small digits*, small digits i.e. 2 or 5 are displayed. If "complete", complete digits are displayed. If "none", no labels are displayed. mirror Determines if the axis lines or/and ticks are mirrored to the opposite side of the plotting area. If True, the axis lines are mirrored. If "ticks", the axis lines and ticks are mirrored. If False, mirroring is disable. If "all", axis lines are mirrored on all shared-axes subplots. If "allticks", axis lines and ticks are mirrored on all shared-axes subplots. modebardisable Disables certain modebar buttons for this axis. "autoscale" disables the autoscale buttons, "zoominout" disables the zoom-in and zoom-out buttons. nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". overlaying If set a same-letter axis id, this axis is overlaid on top of the corresponding same-letter axis, with traces and axes visible for both axes. If False, this axis does not overlay any same-letter axes. In this case, for axes with overlapping domains only the highest- numbered axis will be visible. position Sets the position of this axis in the plotting space (in normalized coordinates). Only has an effect if `anchor` is set to "free". range Sets the range of this axis. If the axis `type` is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. Leaving either or both elements `null` impacts the default `autorange`. rangebreaks A tuple of :class:`plotly.graph_objects.layout.yaxis.Rangebreak` instances or dicts with compatible properties rangebreakdefaults When used in a template (as layout.template.layout.yaxis.rangebreakdefaults), sets the default property values to use for elements of layout.yaxis.rangebreaks rangemode If "normal", the range is computed in relation to the extrema of the input data. If "tozero", the range extends to 0, regardless of the input data If "nonnegative", the range is non-negative, regardless of the input data. Applies only to linear axes. scaleanchor If set to another axis id (e.g. `x2`, `y`), the range of this axis changes together with the range of the corresponding axis such that the scale of pixels per unit is in a constant ratio. Both axes are still zoomable, but when you zoom one, the other will zoom the same amount, keeping a fixed midpoint. `constrain` and `constraintoward` determine how we enforce the constraint. You can chain these, ie `yaxis: {scaleanchor: *x*}, xaxis2: {scaleanchor: *y*}` but you can only link axes of the same `type`. The linked axis can have the opposite letter (to constrain the aspect ratio) or the same letter (to match scales across subplots). Loops (`yaxis: {scaleanchor: *x*}, xaxis: {scaleanchor: *y*}` or longer) are redundant and the last constraint encountered will be ignored to avoid possible inconsistent constraints via `scaleratio`. Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint is currently forbidden. Setting `false` allows to remove a default constraint (occasionally, you may need to prevent a default `scaleanchor` constraint from being applied, eg. when having an image trace `yaxis: {scaleanchor: "x"}` is set automatically in order for pixels to be rendered as squares, setting `yaxis: {scaleanchor: false}` allows to remove the constraint). scaleratio If this axis is linked to another by `scaleanchor`, this determines the pixel to unit scale ratio. For example, if this value is 10, then every unit on this axis spans 10 times the number of pixels as a unit on the linked axis. Use this for example to create an elevation profile where the vertical scale is exaggerated a fixed amount with respect to the horizontal. separatethousands If "true", even 4-digit integers are separated shift Moves the axis a given number of pixels from where it would have been otherwise. Accepts both positive and negative values, which will shift the axis either right or left, respectively. If `autoshift` is set to true, then this defaults to a padding of -3 if `side` is set to "left". and defaults to +3 if `side` is set to "right". Defaults to 0 if `autoshift` is set to false. Only has an effect if `anchor` is set to "free". showdividers Determines whether or not a dividers are drawn between the category levels of this axis. Only has an effect on "multicategory" axes. showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showgrid Determines whether or not grid lines are drawn. If True, the grid lines are drawn at every tick mark. showline Determines whether or not a line bounding this axis is drawn. showspikes Determines whether or not spikes (aka droplines) are drawn for this axis. Note: This only takes affect when hovermode = closest showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. side Determines whether a x (y) axis is positioned at the "bottom" ("left") or "top" ("right") of the plotting area. spikecolor Sets the spike color. If undefined, will use the series color spikedash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). spikemode Determines the drawing mode for the spike line If "toaxis", the line is drawn from the data point to the axis the series is plotted on. If "across", the line is drawn across the entire plot area, and supercedes "toaxis". If "marker", then a marker dot is drawn on the axis the series is plotted on spikesnap Determines whether spikelines are stuck to the cursor or to the closest datapoints. spikethickness Sets the width (in px) of the zero line. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the tick font. tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.layout.yaxis.Ti ckformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.layout.yaxis.tickformatstopdefaults), sets the default property values to use for elements of layout.yaxis.tickformatstops ticklabelindex Only for axes with `type` "date" or "linear". Instead of drawing the major tick label, draw the label for the minor tick that is n positions away from the major tick. E.g. to always draw the label for the minor tick before each major tick, choose `ticklabelindex` -1. This is useful for date axes with `ticklabelmode` "period" if you want to label the period that ends with each major tick instead of the period that begins there. ticklabelindexsrc Sets the source reference on Chart Studio Cloud for `ticklabelindex`. ticklabelmode Determines where tick labels are drawn with respect to their corresponding ticks and grid lines. Only has an effect for axes of `type` "date" When set to "period", tick labels are drawn in the middle of the period between ticks. ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. Otherwise on "category" and "multicategory" axes the default is "allow". In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn with respect to the axis. Please note that top or bottom has no effect on x axes or when `ticklabelmode` is set to "period" or when `tickson` is set to "boundaries". Similarly, left or right has no effect on y axes or when `ticklabelmode` is set to "period" or when `tickson` is set to "boundaries". Has no effect on "multicategory" axes. When used on axes linked by `matches` or `scaleanchor`, no extra padding for inside labels would be added by autorange, so that the scales could match. ticklabelshift Shifts the tick labels by the specified number of pixels in parallel to the axis. Positive values move the labels in the positive direction of the axis. ticklabelstandoff Sets the standoff distance (in px) between the axis tick labels and their default position. A positive `ticklabelstandoff` moves the labels farther away from the plot area if `ticklabelposition` is "outside", and deeper into the plot area if `ticklabelposition` is "inside". A negative `ticklabelstandoff` works in the opposite direction, moving outside ticks towards the plot area and inside ticks towards the outside. If the negative value is large enough, inside ticks can even end up outside and vice versa. ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). If "sync", the number of ticks will sync with the overlayed axis set by `overlaying` property. tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. tickson Determines where ticks and grid lines are drawn with respect to their corresponding tick labels. Only has an effect for axes of `type` "category" or "multicategory". When set to "boundaries", ticks and grid lines are drawn half a category to the left/bottom of labels. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.layout.yaxis.Title` instance or dict with compatible properties type Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question. uirevision Controls persistence of user-driven changes in axis `range`, `autorange`, and `title` if in `editable: true` configuration. Defaults to `layout.uirevision`. unifiedhovertitle :class:`plotly.graph_objects.layout.yaxis.Unifiedhovert itle` instance or dict with compatible properties visible A single toggle to hide the axis while preserving interaction like dragging. Default is true when a cheater plot is present on the axis, otherwise false zeroline Determines whether or not a line is drawn at along the 0 value of this axis. If True, the zero line is drawn on top of the grid lines. zerolinecolor Sets the line color of the zero line. zerolinelayer Sets the layer on which this zeroline is displayed. If *above traces*, this zeroline is displayed above all the subplot's traces If *below traces*, this zeroline is displayed below all the subplot's traces, but above the grid lines. Limitation: "zerolinelayer" currently has no effect if the "zorder" property is set on any trace. zerolinewidth Sets the width (in px) of the zero line. Did you mean "tickfont"? Bad property path: titlefont ^^^^^^^^^ 进程已结束,退出代码为 1 报错了
12-11
<think>根据错误信息,问题出现在`fig.update_layout()`中对`yaxis2`的设置。错误提示说`titlefont`是无效的属性,并建议使用`tickfont`。实际上,在Plotly中设置坐标轴标题字体应该使用`title_font`(注意是下划线)或者直接在`title`属性中使用字典设置字体,例如: ```python yaxis2=dict( title="品牌占比", titlefont=dict(color="#d62728"), # 这里应该改为title_font或者使用title属性中的font ... ) ``` 但是,根据最新的Plotly文档,正确的做法是在`title`属性中设置字体,或者使用`title_font`(在更新坐标轴属性时,`title_font`是一个独立的属性)。不过,在`update_layout`中使用`yaxis2_title_font`这样的形式也是可以的。 然而,错误信息中列出了所有有效的属性,其中并没有`titlefont`,而是有`title`(它是一个包含`font`等属性的对象)和`title_font`(用于直接设置标题字体)。 因此,我们需要修改代码: 1. 对于`yaxis2`的标题颜色设置,我们可以使用: ```python yaxis2=dict( title="品牌占比", title_font=dict(color="#d62728"), ... ) ``` 2. 另外,错误信息还提示了另一个问题:在代码中我们使用了`titlefont`,应该改为`title_font`(注意是下划线)。 让我们修正代码中的这个问题。同时,我还注意到在创建`yaxis2`时,我们覆盖了主Y轴(yaxis)的配置?实际上,我们不应该在`update_layout`中直接设置`yaxis2`的`titlefont`,而应该使用`yaxis2_title_font`,或者使用`yaxis2=dict(...)`。但我们在同一个`update_layout`中同时设置了`yaxis2`字典和`yaxis2_title_font`是不行的,应该采用统一的方式。 这里我们采用在`update_layout`中直接设置`yaxis2`字典的方式,并在其中使用`title_font`。 修正部分代码: ```python # 添加右侧Y轴 fig.update_layout( yaxis2=dict( title="品牌占比", title_font=dict(color="#d62728"), tickfont=dict(color="#d62728"), overlaying="y", side="right", range=[0, 1] ) ) ``` 另外,在错误信息之前还有一个警告:`SettingWithCopyWarning`,这通常是因为我们试图在DataFrame的切片上赋值。为了避免这个警告,我们应该使用`.loc`来赋值。 在代码中,我们有一行: ```python jan_data['XM占比'] = jan_data['XM品牌预测值'] / jan_data['月度大盘预测值'] ``` 可以改为: ```python jan_data.loc[:, 'XM占比'] = jan_data['XM品牌预测值'] / jan_data['月度大盘预测值'] ``` 这样应该能避免警告。 现在,让我们整合这些修正,重新写一下代码。 由于原始代码较长,我仅重写有问题的部分,并给出完整代码: ```python import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots # 读取Excel文件 df = pd.read_excel('your_data.xlsx') # 替换为实际文件路径 # 转换日期列 df['forecast_time'] = pd.to_datetime(df['forecast_time']) df['date'] = pd.to_datetime(df['date']) # 提取2025/1/1期次的数据 jan_data = df[df['forecast_time'] == '2025-01-01'].copy() # 使用copy()避免SettingWithCopyWarning # 提取2025/11/1期次的数据 nov_data = df[df['forecast_time'] == '2025-11-01'].copy() # 计算XM品牌占比,使用loc避免警告 jan_data.loc[:, 'XM占比'] = jan_data['XM品牌预测值'] / jan_data['月度大盘预测值'] # 创建包含多个子图的HTML页面 fig = make_subplots( rows=3, cols=2, specs=[ [{"type": "bar", "rowspan": 2}, {"type": "scatter"}], [None, {"type": "pie"}], [{"type": "bar"}, {"type": "pie"}] ], subplot_titles=( "大盘销量趋势与XM品牌占比", "预测准确率(ACC)变化趋势", "大盘价格档位占比(2025/1/1期次)", "2025/11/1期次销量预测", "XM品牌价格档位占比(2025/1/1期次)" ), vertical_spacing=0.1, horizontal_spacing=0.15 ) # 图1: 大盘趋势和XM品牌占比 (重叠柱状图) fig.add_trace( go.Bar( x=jan_data['date'], y=jan_data['月度大盘预测值'], name='大盘预测值', marker_color='#1f77b4', opacity=0.7 ), row=1, col=1 ) fig.add_trace( go.Bar( x=jan_data['date'], y=jan_data['月度大盘真实值'], name='大盘真实值', marker_color='#ff7f0e', opacity=0.7 ), row=1, col=1 ) fig.add_trace( go.Scatter( x=jan_data['date'], y=jan_data['XM占比'], name='XM品牌占比', mode='lines+markers', line=dict(color='#d62728', width=3), yaxis='y2' ), row=1, col=1 ) # 添加右侧Y轴配置 fig.update_layout( yaxis2=dict( title="品牌占比", title_font=dict(color="#d62728"), tickfont=dict(color="#d62728"), overlaying="y", side="right", range=[0, 1] ) ) # 图2: 预测准确率变化 fig.add_trace( go.Scatter( x=jan_data['date'], y=jan_data['ACC'], name='大盘ACC', mode='lines+markers', line=dict(color='#2ca02c', width=2) ), row=1, col=2 ) fig.add_trace( go.Scatter( x=jan_data['date'], y=jan_data['ACC.1'], name='XM品牌ACC', mode='lines+markers', line=dict(color='#9467bd', width=2) ), row=1, col=2 ) # 图3: 大盘价格档位占比 (2025/1/1期次的最后一个月) last_month = jan_data.iloc[-1] # 获取最后一个月的数据 price_bins = ['0-1000', '1000-2000', '2000-3000', '3000-4000', '4000-6000', '6000+'] pred_values = [ last_month['月度0-1000预测'], last_month['月度1000-2000预测'], last_month['月度2000-3000预测'], last_month['月度3000-4000预测'], last_month['月度4000-6000预测'], last_month['月度6000-99999预测'] ] fig.add_trace( go.Pie( labels=price_bins, values=pred_values, name='大盘价格档位', hole=0.4, marker_colors=['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462'] ), row=2, col=2 ) # 图4: 2025/11/1期次销量预测 # 注意:这里我们使用nov_data,并且取每个价格档位的预测值的平均值(因为nov_data可能有多个月份?) # 但根据问题描述,每个期次的数据包含从预测时间到2027-12-01的月份,所以nov_data中也有多个月份 # 我们这里展示的是nov_data中所有月份的平均值?还是只展示某一特定月份? # 根据需求,是“2025/11/1期次的数据”,并且要表现预测销量和占比。这里我们可能想展示该期次预测的最后一个月份(即2027-12-01)? # 或者展示该期次预测的所有月份的平均?但原需求没有明确,这里暂时按原代码取平均。 # 但原需求是“最后再用2025/11/1的期次的数据,表现一下预测的数据的销量和之间的占比,以及各个档位的信息” # 这里我们展示该期次预测的最后一个月份(即2027-12-01)的各档位预测值 # 修改:从nov_data中取最后一个月份 last_month_nov = nov_data.iloc[-1] fig.add_trace( go.Bar( x=price_bins, y=[ last_month_nov['月度0-1000预测'], last_month_nov['月度1000-2000预测'], last_month_nov['月度2000-3000预测'], last_month_nov['月度3000-4000预测'], last_month_nov['月度4000-6000预测'], last_month_nov['月度6000-99999预测'] ], name='2025/11/1期次预测(2027-12)', marker_color='#17becf' ), row=3, col=1 ) # 图5: XM品牌价格档位占比 (2025/1/1期次的最后一个月) xm_pred_values = [ last_month['XM0-1000预测'], last_month['XM1000-2000预测'], last_month['XM2000-3000预测'], last_month['XM3000-4000预测'], last_month['XM4000-6000预测'], last_month['XM6000-99999预测'] ] fig.add_trace( go.Pie( labels=price_bins, values=xm_pred_values, name='XM品牌价格档位', hole=0.4, marker_colors=['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462'] ), row=3, col=2 ) # 更新整体布局 fig.update_layout( title_text='销售预测数据分析报告 (2025/1/1 和 2025/11/1 期次)', height=1200, width=1400, showlegend=True, template='plotly_white' ) # 更新子图布局 fig.update_xaxes(title_text="日期", row=1, col=1) fig.update_yaxes(title_text="销量", row=1, col=1) fig.update_xaxes(title_text="日期", row=1, col=2) fig.update_yaxes(title_text="ACC值", row=1, col=2) fig.update_xaxes(title_text="价格档位", row=3, col=1) fig.update_yaxes(title_text="预测销量", row=3, col=1) # 保存为HTML文件 fig.write_html('sales_forecast_analysis.html', auto_open=True) ``` 主要修改点: 1. 使用`.copy()`避免`SettingWithCopyWarning`,并在计算占比时使用`.loc`。 2. 修正了`yaxis2`的配置,将`titlefont`改为`title_font`(并放在`yaxis2`字典内)。 3. 对于2025/11/1期次的柱状图,之前是取平均值,现在改为取该期次最后一个月份(2027-12-01)的数据。这样更符合需求,因为需求是“表现一下预测的数据的销量和之间的占比,以及各个档位的信息”。当然,如果需求是展示该期次所有月份的平均,那么可以改回平均值。这里根据需求描述,我理解为展示该期次预测的最后一个时间点(即2027-12-01)的情况。 注意:如果nov_data中没有数据(即没有2027-12-01这个月份),那么需要调整。根据问题描述,所有预测时间的截至都是2027/12/1,所以每个期次的数据应该都包含到2027-12-01。 如果还有问题,请根据实际情况调整。 §§相关问题§§: 1. 在Plotly中如何避免SettingWithCopyWarning? 2. 在Plotly中设置双Y轴时,如何正确配置第二个Y轴的属性? 3. 如何处理时间序列数据在Plotly中的展示,特别是当数据点很多时? 4. 在Plotly中,如何动态更新图表以展示不同期次的数据? </think> 这个错误是由于在Plotly中使用了无效的属性名`titlefont`导致的。根据错误信息,Plotly建议使用`tickfont`,但实际上我们需要的是设置坐标轴标题的字体颜色,正确的方式是使用`title_font`属性(注意是下划线分隔)。 ### 修正后的代码 以下是修正后的完整代码,解决了属性名错误问题: ```python import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots # 读取Excel文件 df = pd.read_excel('your_data.xlsx') # 替换为实际文件路径 # 转换日期列 df['forecast_time'] = pd.to_datetime(df['forecast_time']) df['date'] = pd.to_datetime(df['date']) # 提取2025/1/1期次的数据 jan_data = df[df['forecast_time'] == '2025-01-01'].copy() # 使用copy避免SettingWithCopyWarning # 提取2025/11/1期次的数据 nov_data = df[df['forecast_time'] == '2025-11-01'].copy() # 创建包含多个子图的HTML页面 fig = make_subplots( rows=3, cols=2, specs=[ [{"type": "bar", "rowspan": 2}, {"type": "scatter"}], [None, {"type": "pie"}], [{"type": "bar"}, {"type": "pie"}] ], subplot_titles=( "大盘销量趋势与XM品牌占比", "预测准确率(ACC)变化趋势", "大盘价格档位占比(2025/1/1期次)", "2025/11/1期次销量预测", "XM品牌价格档位占比(2025/1/1期次)" ), vertical_spacing=0.1, horizontal_spacing=0.15 ) # 图1: 大盘趋势和XM品牌占比 (重叠柱状图) fig.add_trace( go.Bar( x=jan_data['date'], y=jan_data['月度大盘预测值'], name='大盘预测值', marker_color='#1f77b4', opacity=0.7 ), row=1, col=1 ) fig.add_trace( go.Bar( x=jan_data['date'], y=jan_data['月度大盘真实值'], name='大盘真实值', marker_color='#ff7f0e', opacity=0.7 ), row=1, col=1 ) # 计算XM品牌占比 jan_data.loc[:, 'XM占比'] = jan_data['XM品牌预测值'] / jan_data['月度大盘预测值'] # 使用loc避免警告 fig.add_trace( go.Scatter( x=jan_data['date'], y=jan_data['XM占比'], name='XM品牌占比', mode='lines+markers', line=dict(color='#d62728', width=3), yaxis='y2' ), row=1, col=1 ) # 添加右侧Y轴 - 修正属性名错误 fig.update_layout( yaxis2=dict( title="品牌占比", title_font=dict(color="#d62728"), # 修正:使用title_font代替titlefont tickfont=dict(color="#d62728"), overlaying="y", side="right", range=[0, 1] ) ) # 图2: 预测准确率变化 fig.add_trace( go.Scatter( x=jan_data['date'], y=jan_data['ACC'], name='大盘ACC', mode='lines+markers', line=dict(color='#2ca02c', width=2) ), row=1, col=2 ) fig.add_trace( go.Scatter( x=jan_data['date'], y=jan_data['ACC.1'], name='XM品牌ACC', mode='lines+markers', line=dict(color='#9467bd', width=2) ), row=1, col=2 ) # 图3: 大盘价格档位占比 (2025/1/1期次的最后一个月) last_month = jan_data.iloc[-1] # 获取最后一个月的数据 price_bins = ['0-1000', '1000-2000', '2000-3000', '3000-4000', '4000-6000', '6000+'] pred_values = [ last_month['月度0-1000预测'], last_month['月度1000-2000预测'], last_month['月度2000-3000预测'], last_month['月度3000-4000预测'], last_month['月度4000-6000预测'], last_month['月度6000-99999预测'] ] fig.add_trace( go.Pie( labels=price_bins, values=pred_values, name='大盘价格档位', hole=0.4, marker_colors=['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462'] ), row=2, col=2 ) # 图4: 2025/11/1期次销量预测 fig.add_trace( go.Bar( x=price_bins, y=[ nov_data['月度0-1000预测'].mean(), nov_data['月度1000-2000预测'].mean(), nov_data['月度2000-3000预测'].mean(), nov_data['月度3000-4000预测'].mean(), nov_data['月度4000-6000预测'].mean(), nov_data['月度6000-99999预测'].mean() ], name='2025/11/1期次预测', marker_color='#17becf' ), row=3, col=1 ) # 图5: XM品牌价格档位占比 (2025/1/1期次的最后一个月) xm_pred_values = [ last_month['XM0-1000预测'], last_month['XM1000-2000预测'], last_month['XM2000-3000预测'], last_month['XM3000-4000预测'], last_month['XM4000-6000预测'], last_month['XM6000-99999预测'] ] fig.add_trace( go.Pie( labels=price_bins, values=xm_pred_values, name='XM品牌价格档位', hole=0.4, marker_colors=['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462'] ), row=3, col=2 ) # 更新整体布局 fig.update_layout( title_text='销售预测数据分析报告 (2025/1/1 和 2025/11/1 期次)', height=1200, width=1400, showlegend=True, template='plotly_white' ) # 更新子图布局 fig.update_xaxes(title_text="日期", row=1, col=1) fig.update_yaxes(title_text="销量", row=1, col=1) fig.update_xaxes(title_text="日期", row=1, col=2) fig.update_yaxes(title_text="ACC值", row=1, col=2) fig.update_xaxes(title_text="价格档位", row=3, col=1) fig.update_yaxes(title_text="平均销量", row=3, col=1) # 保存为HTML文件 fig.write_html('sales_forecast_analysis.html', auto_open=True) ``` ### 主要修正点: 1. **属性名修正**: - 将错误的`titlefont`改为正确的`title_font` - 使用`title_font=dict(color="#d62728")`设置坐标轴标题字体颜色 2. **避免SettingWithCopyWarning**: - 使用`.copy()`创建数据子集副本 - 使用`jan_data.loc[:, 'XM占比'] = ...`语法避免警告 3. **其他改进**: - 保持图表布局和功能不变 - 添加了注释说明关键修改点 ### 运行前准备: 1. 确保安装依赖:`pip install pandas plotly openpyxl` 2. 将代码中的`'your_data.xlsx'`替换为实际Excel文件路径 这个修正版本应该能解决之前的属性名错误问题,并避免产生SettingWithCopyWarning。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值